Doc: Modularize QtNetwork documentation.
[profile/ivi/qtbase.git] / src / network / socket / qnativesocketengine.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 //#define QNATIVESOCKETENGINE_DEBUG
43
44 /*! \class QNativeSocketEngine
45     \internal
46
47     \brief The QNativeSocketEngine class provides low level access to a socket.
48
49     \reentrant
50     \ingroup network
51     \inmodule QtNetwork
52
53     QtSocketLayer provides basic socket functionality provided by the
54     operating system. It also keeps track of what state the socket is
55     in, and which errors that occur.
56
57     The classes QTcpSocket, QUdpSocket and QTcpServer provide a
58     higher level API, and are in general more useful for the common
59     application.
60
61     There are two main ways of initializing the a QNativeSocketEngine; either
62     create a new socket by passing the socket type (TcpSocket or
63     UdpSocket) and network layer protocol (IPv4Protocol or
64     IPv6Protocol) to initialize(), or pass an existing socket
65     descriptor and have QNativeSocketEngine determine the type and protocol
66     itself. The native socket descriptor can later be fetched by
67     calling socketDescriptor(). The socket is made non-blocking, but
68     blocking behavior can still be achieved by calling waitForRead()
69     and waitForWrite(). isValid() can be called to check if the socket
70     has been successfully initialized and is ready to use.
71
72     To connect to a host, determine its address and pass this and the
73     port number to connectToHost(). The socket can then be used as a
74     TCP or UDP client. Otherwise; bind(), listen() and accept() are
75     used to have the socket function as a TCP or UDP server. Call
76     close() to close the socket.
77
78     bytesAvailable() is called to determine how much data is available
79     for reading. read() and write() are used by both TCP and UDP
80     clients to exchange data with the connected peer. UDP clients can
81     also call hasMoreDatagrams(), nextDatagramSize(),
82     readDatagram(), and writeDatagram().
83
84     Call state() to determine the state of the socket, for
85     example, ListeningState or ConnectedState. socketType() tells
86     whether the socket is a TCP socket or a UDP socket, or if the
87     socket type is unknown. protocol() is used to determine the
88     socket's network layer protocol.
89
90     localAddress(), localPort() are called to find the address and
91     port that are currently bound to the socket. If the socket is
92     connected, peerAddress() and peerPort() determine the address and
93     port of the connected peer.
94
95     Finally, if any function should fail, error() and
96     errorString() can be called to determine the cause of the error.
97 */
98
99 #include <qabstracteventdispatcher.h>
100 #include <qsocketnotifier.h>
101 #include <qnetworkinterface.h>
102
103 #include "qnativesocketengine_p.h"
104 #include <private/qthread_p.h>
105 #include <private/qobject_p.h>
106
107 #if !defined(QT_NO_NETWORKPROXY)
108 # include "qnetworkproxy.h"
109 # include "qabstractsocket.h"
110 # include "qtcpserver.h"
111 #endif
112
113 QT_BEGIN_NAMESPACE
114
115 //#define QNATIVESOCKETENGINE_DEBUG
116
117 #define Q_VOID
118
119 // Common constructs
120 #define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \
121     if (!isValid()) { \
122         qWarning(""#function" was called on an uninitialized socket device"); \
123         return returnValue; \
124     } } while (0)
125 #define Q_CHECK_INVALID_SOCKETLAYER(function, returnValue) do { \
126     if (isValid()) { \
127         qWarning(""#function" was called on an already initialized socket device"); \
128         return returnValue; \
129     } } while (0)
130 #define Q_CHECK_STATE(function, checkState, returnValue) do { \
131     if (d->socketState != (checkState)) { \
132         qWarning(""#function" was not called in "#checkState); \
133         return (returnValue); \
134     } } while (0)
135 #define Q_CHECK_NOT_STATE(function, checkState, returnValue) do { \
136     if (d->socketState == (checkState)) { \
137         qWarning(""#function" was called in "#checkState); \
138         return (returnValue); \
139     } } while (0)
140 #define Q_CHECK_STATES(function, state1, state2, returnValue) do { \
141     if (d->socketState != (state1) && d->socketState != (state2)) { \
142         qWarning(""#function" was called" \
143                  " not in "#state1" or "#state2); \
144         return (returnValue); \
145     } } while (0)
146 #define Q_CHECK_TYPE(function, type, returnValue) do { \
147     if (d->socketType != (type)) { \
148         qWarning(#function" was called by a" \
149                  " socket other than "#type""); \
150         return (returnValue); \
151     } } while (0)
152 #define Q_TR(a) QT_TRANSLATE_NOOP(QNativeSocketEngine, a)
153
154 /*! \internal
155     Constructs the private class and initializes all data members.
156
157     On Windows, WSAStartup is called "recursively" for every
158     concurrent QNativeSocketEngine. This is safe, because WSAStartup and
159     WSACleanup are reference counted.
160 */
161 QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() :
162     socketDescriptor(-1),
163     readNotifier(0),
164     writeNotifier(0),
165     exceptNotifier(0)
166 {
167 }
168
169 /*! \internal
170     Destructs the private class.
171 */
172 QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate()
173 {
174 }
175
176 /*! \internal
177
178     Sets the error and error string if not set already. The only
179     interesting error is the first one that occurred, and not the last
180     one.
181 */
182 void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const
183 {
184     if (hasSetSocketError) {
185         // Only set socket errors once for one engine; expect the
186         // socket to recreate its engine after an error. Note: There's
187         // one exception: SocketError(11) bypasses this as it's purely
188         // a temporary internal error condition.
189         // Another exception is the way the waitFor*() functions set
190         // an error when a timeout occurs. After the call to setError()
191         // they reset the hasSetSocketError to false
192         return;
193     }
194     if (error != QAbstractSocket::SocketError(11))
195         hasSetSocketError = true;
196
197     socketError = error;
198
199     switch (errorString) {
200     case NonBlockingInitFailedErrorString:
201         socketErrorString = QNativeSocketEngine::tr("Unable to initialize non-blocking socket");
202         break;
203     case BroadcastingInitFailedErrorString:
204         socketErrorString = QNativeSocketEngine::tr("Unable to initialize broadcast socket");
205         break;
206     // should not happen anymore
207     case NoIpV6ErrorString:
208         socketErrorString = QNativeSocketEngine::tr("Attempt to use IPv6 socket on a platform with no IPv6 support");
209         break;
210     case RemoteHostClosedErrorString:
211         socketErrorString = QNativeSocketEngine::tr("The remote host closed the connection");
212         break;
213     case TimeOutErrorString:
214         socketErrorString = QNativeSocketEngine::tr("Network operation timed out");
215         break;
216     case ResourceErrorString:
217         socketErrorString = QNativeSocketEngine::tr("Out of resources");
218         break;
219     case OperationUnsupportedErrorString:
220         socketErrorString = QNativeSocketEngine::tr("Unsupported socket operation");
221         break;
222     case ProtocolUnsupportedErrorString:
223         socketErrorString = QNativeSocketEngine::tr("Protocol type not supported");
224         break;
225     case InvalidSocketErrorString:
226         socketErrorString = QNativeSocketEngine::tr("Invalid socket descriptor");
227         break;
228     case HostUnreachableErrorString:
229         socketErrorString = QNativeSocketEngine::tr("Host unreachable");
230         break;
231     case NetworkUnreachableErrorString:
232         socketErrorString = QNativeSocketEngine::tr("Network unreachable");
233         break;
234     case AccessErrorString:
235         socketErrorString = QNativeSocketEngine::tr("Permission denied");
236         break;
237     case ConnectionTimeOutErrorString:
238         socketErrorString = QNativeSocketEngine::tr("Connection timed out");
239         break;
240     case ConnectionRefusedErrorString:
241         socketErrorString = QNativeSocketEngine::tr("Connection refused");
242         break;
243     case AddressInuseErrorString:
244         socketErrorString = QNativeSocketEngine::tr("The bound address is already in use");
245         break;
246     case AddressNotAvailableErrorString:
247         socketErrorString = QNativeSocketEngine::tr("The address is not available");
248         break;
249     case AddressProtectedErrorString:
250         socketErrorString = QNativeSocketEngine::tr("The address is protected");
251         break;
252     case DatagramTooLargeErrorString:
253         socketErrorString = QNativeSocketEngine::tr("Datagram was too large to send");
254         break;
255     case SendDatagramErrorString:
256         socketErrorString = QNativeSocketEngine::tr("Unable to send a message");
257         break;
258     case ReceiveDatagramErrorString:
259         socketErrorString = QNativeSocketEngine::tr("Unable to receive a message");
260         break;
261     case WriteErrorString:
262         socketErrorString = QNativeSocketEngine::tr("Unable to write");
263         break;
264     case ReadErrorString:
265         socketErrorString = QNativeSocketEngine::tr("Network error");
266         break;
267     case PortInuseErrorString:
268         socketErrorString = QNativeSocketEngine::tr("Another socket is already listening on the same port");
269         break;
270     case NotSocketErrorString:
271         socketErrorString = QNativeSocketEngine::tr("Operation on non-socket");
272         break;
273     case InvalidProxyTypeString:
274         socketErrorString = QNativeSocketEngine::tr("The proxy type is invalid for this operation");
275         break;
276     case UnknownSocketErrorString:
277         socketErrorString = QNativeSocketEngine::tr("Unknown error");
278         break;
279     }
280 }
281
282 bool QNativeSocketEnginePrivate::checkProxy(const QHostAddress &address)
283 {
284     if (address.isLoopback())
285         return true;
286
287 #if !defined(QT_NO_NETWORKPROXY)
288     QObject *parent = q_func()->parent();
289     QNetworkProxy proxy;
290     if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(parent)) {
291         proxy = socket->proxy();
292     } else if (QTcpServer *server = qobject_cast<QTcpServer *>(parent)) {
293         proxy = server->proxy();
294     } else {
295         // no parent -> no proxy
296         return true;
297     }
298
299     if (proxy.type() == QNetworkProxy::DefaultProxy)
300         proxy = QNetworkProxy::applicationProxy();
301
302     if (proxy.type() != QNetworkProxy::DefaultProxy &&
303         proxy.type() != QNetworkProxy::NoProxy) {
304         // QNativeSocketEngine doesn't do proxies
305         setError(QAbstractSocket::UnsupportedSocketOperationError,
306                  QNativeSocketEnginePrivate::InvalidProxyTypeString);
307         return false;
308     }
309 #endif
310
311     return true;
312 }
313
314 /*!
315     Constructs a QNativeSocketEngine.
316
317     \sa initialize()
318 */
319 QNativeSocketEngine::QNativeSocketEngine(QObject *parent)
320     : QAbstractSocketEngine(*new QNativeSocketEnginePrivate(), parent)
321 {
322 }
323
324 /*!
325     Destructs a QNativeSocketEngine.
326 */
327 QNativeSocketEngine::~QNativeSocketEngine()
328 {
329     close();
330 }
331
332 /*!
333     Initializes a QNativeSocketEngine by creating a new socket of type \a
334     socketType and network layer protocol \a protocol. Returns true on
335     success; otherwise returns false.
336
337     If the socket was already initialized, this function closes the
338     socket before reeinitializing it.
339
340     The new socket is non-blocking, and for UDP sockets it's also
341     broadcast enabled.
342 */
343 bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol protocol)
344 {
345     Q_D(QNativeSocketEngine);
346     if (isValid())
347         close();
348
349     // Create the socket
350     if (!d->createNewSocket(socketType, protocol)) {
351 #if defined (QNATIVESOCKETENGINE_DEBUG)
352         QString typeStr = QLatin1String("UnknownSocketType");
353         if (socketType == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
354         else if (socketType == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
355         QString protocolStr = QLatin1String("UnknownProtocol");
356         if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
357         else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
358         qDebug("QNativeSocketEngine::initialize(type == %s, protocol == %s) failed: %s",
359                typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(), d->socketErrorString.toLatin1().constData());
360 #endif
361         return false;
362     }
363
364     // Make the socket nonblocking.
365     if (!setOption(NonBlockingSocketOption, 1)) {
366         d->setError(QAbstractSocket::UnsupportedSocketOperationError,
367                     QNativeSocketEnginePrivate::NonBlockingInitFailedErrorString);
368         close();
369         return false;
370     }
371
372     // Set the broadcasting flag if it's a UDP socket.
373     if (socketType == QAbstractSocket::UdpSocket
374         && !setOption(BroadcastSocketOption, 1)) {
375         d->setError(QAbstractSocket::UnsupportedSocketOperationError,
376                     QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
377         close();
378         return false;
379     }
380
381
382     // Make sure we receive out-of-band data
383     if (socketType == QAbstractSocket::TcpSocket
384         && !setOption(ReceiveOutOfBandData, 1)) {
385         qWarning("QNativeSocketEngine::initialize unable to inline out-of-band data");
386     }
387
388     // Before Qt 4.6, we always set the send and receive buffer size to 49152 as
389     // this was found to be an optimal value. However, modern OS
390     // all have some kind of auto tuning for this and we therefore don't set
391     // this explictly anymore.
392     // If it introduces any performance regressions for Qt 4.6.x (x > 0) then
393     // it will be put back in.
394     //
395     // You can use tests/manual/qhttpnetworkconnection to test HTTP download speed
396     // with this.
397     //
398     // pre-4.6:
399     // setReceiveBufferSize(49152);
400     // setSendBufferSize(49152);
401
402     d->socketType = socketType;
403     d->socketProtocol = protocol;
404     return true;
405 }
406
407 /*! \overload
408
409     Initializes the socket using \a socketDescriptor instead of
410     creating a new one. The socket type and network layer protocol are
411     determined automatically. The socket's state is set to \a
412     socketState.
413
414     If the socket type is either TCP or UDP, it is made non-blocking.
415     UDP sockets are also broadcast enabled.
416  */
417 bool QNativeSocketEngine::initialize(qintptr socketDescriptor, QAbstractSocket::SocketState socketState)
418 {
419     Q_D(QNativeSocketEngine);
420
421     if (isValid())
422         close();
423
424     d->socketDescriptor = socketDescriptor;
425
426     // determine socket type and protocol
427     if (!d->fetchConnectionParameters()) {
428 #if defined (QNATIVESOCKETENGINE_DEBUG)
429         qDebug("QNativeSocketEngine::initialize(socketDescriptor == %i) failed: %s",
430                socketDescriptor, d->socketErrorString.toLatin1().constData());
431 #endif
432         d->socketDescriptor = -1;
433         return false;
434     }
435
436     if (d->socketType != QAbstractSocket::UnknownSocketType) {
437         // Make the socket nonblocking.
438         if (!setOption(NonBlockingSocketOption, 1)) {
439             d->setError(QAbstractSocket::UnsupportedSocketOperationError,
440                 QNativeSocketEnginePrivate::NonBlockingInitFailedErrorString);
441             close();
442             return false;
443         }
444
445         // Set the broadcasting flag if it's a UDP socket.
446         if (d->socketType == QAbstractSocket::UdpSocket
447             && !setOption(BroadcastSocketOption, 1)) {
448             d->setError(QAbstractSocket::UnsupportedSocketOperationError,
449                 QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
450             close();
451             return false;
452         }
453     }
454
455     d->socketState = socketState;
456     return true;
457 }
458
459 /*!
460     Returns true if the socket is valid; otherwise returns false. A
461     socket is valid if it has not been successfully initialized, or if
462     it has been closed.
463 */
464 bool QNativeSocketEngine::isValid() const
465 {
466     Q_D(const QNativeSocketEngine);
467     return d->socketDescriptor != -1;
468 }
469
470 /*!
471     Returns the native socket descriptor. Any use of this descriptor
472     stands the risk of being non-portable.
473 */
474 qintptr QNativeSocketEngine::socketDescriptor() const
475 {
476     Q_D(const QNativeSocketEngine);
477     return d->socketDescriptor;
478 }
479
480 /*!
481     Connects to the IP address and port specified by \a address and \a
482     port. If the connection is established, this function returns true
483     and the socket enters ConnectedState. Otherwise, false is
484     returned.
485
486     If false is returned, state() should be called to see if the
487     socket is in ConnectingState. If so, a delayed TCP connection is
488     taking place, and connectToHost() must be called again later to
489     determine if the connection was established successfully or
490     not. The second connection attempt must be made when the socket is
491     ready for writing. This state can be determined either by
492     connecting a QSocketNotifier to the socket descriptor returned by
493     socketDescriptor(), or by calling the blocking function
494     waitForWrite().
495
496     Example:
497     \snippet code/src_network_socket_qnativesocketengine.cpp 0
498
499     Otherwise, error() should be called to determine the cause of the
500     error.
501 */
502 bool QNativeSocketEngine::connectToHost(const QHostAddress &address, quint16 port)
503 {
504     Q_D(QNativeSocketEngine);
505     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::connectToHost(), false);
506
507     if (!d->checkProxy(address))
508         return false;
509
510     Q_CHECK_STATES(QNativeSocketEngine::connectToHost(),
511                    QAbstractSocket::UnconnectedState, QAbstractSocket::ConnectingState, false);
512
513     d->peerAddress = address;
514     d->peerPort = port;
515     bool connected = d->nativeConnect(address, port);
516     if (connected)
517         d->fetchConnectionParameters();
518
519     return connected;
520 }
521
522 /*!
523     If there's a connection activity on the socket, process it. Then
524     notify our parent if there really was activity.
525 */
526 void QNativeSocketEngine::connectionNotification()
527 {
528     Q_D(QNativeSocketEngine);
529     Q_ASSERT(state() == QAbstractSocket::ConnectingState);
530
531     connectToHost(d->peerAddress, d->peerPort);
532     if (state() != QAbstractSocket::ConnectingState) {
533         // we changed states
534         QAbstractSocketEngine::connectionNotification();
535     }
536 }
537
538 /*!
539     Connects to the remote host name given by \a name on port \a
540     port. When this function is called, the upper-level will not
541     perform a hostname lookup.
542
543     The native socket engine does not support this operation,
544     but some other socket engines (notably proxy-based ones) do.
545 */
546 bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port)
547 {
548     Q_UNUSED(name);
549     Q_UNUSED(port);
550     Q_D(QNativeSocketEngine);
551     d->setError(QAbstractSocket::UnsupportedSocketOperationError,
552                 QNativeSocketEnginePrivate::OperationUnsupportedErrorString);
553     return false;
554 }
555
556 /*!
557     Binds the socket to the address \a address and port \a
558     port. Returns true on success; otherwise false is returned. The
559     port may be 0, in which case an arbitrary unused port is assigned
560     automatically by the operating system.
561
562     Servers call this function to set up the server's address and
563     port. TCP servers must in addition call listen() after bind().
564 */
565 bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
566 {
567     Q_D(QNativeSocketEngine);
568     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::bind(), false);
569
570     if (!d->checkProxy(address))
571         return false;
572
573     Q_CHECK_STATE(QNativeSocketEngine::bind(), QAbstractSocket::UnconnectedState, false);
574
575     if (!d->nativeBind(address, port))
576         return false;
577
578     d->fetchConnectionParameters();
579     return true;
580 }
581
582 /*!
583     Prepares a TCP server for accepting incoming connections. This
584     function must be called after bind(), and only by TCP sockets.
585
586     After this function has been called, pending client connections
587     are detected by checking if the socket is ready for reading. This
588     can be done by either creating a QSocketNotifier, passing the
589     socket descriptor returned by socketDescriptor(), or by calling
590     the blocking function waitForRead().
591
592     Example:
593     \snippet code/src_network_socket_qnativesocketengine.cpp 1
594
595     \sa bind(), accept()
596 */
597 bool QNativeSocketEngine::listen()
598 {
599     Q_D(QNativeSocketEngine);
600     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::listen(), false);
601     Q_CHECK_STATE(QNativeSocketEngine::listen(), QAbstractSocket::BoundState, false);
602     Q_CHECK_TYPE(QNativeSocketEngine::listen(), QAbstractSocket::TcpSocket, false);
603
604     // We're using a backlog of 50. Most modern kernels support TCP
605     // syncookies by default, and if they do, the backlog is ignored.
606     // When there is no support for TCP syncookies, this value is
607     // fine.
608     return d->nativeListen(50);
609 }
610
611 /*!
612     Accepts a pending connection from the socket, which must be in
613     ListeningState, and returns its socket descriptor. If no pending
614     connections are available, -1 is returned.
615
616     \sa bind(), listen()
617 */
618 int QNativeSocketEngine::accept()
619 {
620     Q_D(QNativeSocketEngine);
621     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::accept(), -1);
622     Q_CHECK_STATE(QNativeSocketEngine::accept(), QAbstractSocket::ListeningState, false);
623     Q_CHECK_TYPE(QNativeSocketEngine::accept(), QAbstractSocket::TcpSocket, false);
624
625     return d->nativeAccept();
626 }
627
628 #ifndef QT_NO_NETWORKINTERFACE
629
630 /*!
631     \since 4.8
632 */
633 bool QNativeSocketEngine::joinMulticastGroup(const QHostAddress &groupAddress,
634                                              const QNetworkInterface &iface)
635 {
636     Q_D(QNativeSocketEngine);
637     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::joinMulticastGroup(), false);
638     Q_CHECK_STATE(QNativeSocketEngine::joinMulticastGroup(), QAbstractSocket::BoundState, false);
639     Q_CHECK_TYPE(QNativeSocketEngine::joinMulticastGroup(), QAbstractSocket::UdpSocket, false);
640
641     // if the user binds a socket to an IPv6 address (or QHostAddress::Any) and
642     // then attempts to join an IPv4 multicast group, this won't work on
643     // Windows. In order to make this cross-platform, we warn & fail on all
644     // platforms.
645     if (groupAddress.protocol() == QAbstractSocket::IPv4Protocol &&
646         (d->socketProtocol == QAbstractSocket::IPv6Protocol ||
647          d->socketProtocol == QAbstractSocket::AnyIPProtocol)) {
648         qWarning("QAbstractSocket: cannot bind to QHostAddress::Any (or an IPv6 address) and join an IPv4 multicast group");
649         qWarning("QAbstractSocket: bind to QHostAddress::AnyIPv4 instead if you want to do this");
650         return false;
651     }
652
653     return d->nativeJoinMulticastGroup(groupAddress, iface);
654 }
655
656 /*!
657     \since 4.8
658 */
659 bool QNativeSocketEngine::leaveMulticastGroup(const QHostAddress &groupAddress,
660                                               const QNetworkInterface &iface)
661 {
662     Q_D(QNativeSocketEngine);
663     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::leaveMulticastGroup(), false);
664     Q_CHECK_STATE(QNativeSocketEngine::leaveMulticastGroup(), QAbstractSocket::BoundState, false);
665     Q_CHECK_TYPE(QNativeSocketEngine::leaveMulticastGroup(), QAbstractSocket::UdpSocket, false);
666     return d->nativeLeaveMulticastGroup(groupAddress, iface);
667 }
668
669 /*! \since 4.8 */
670 QNetworkInterface QNativeSocketEngine::multicastInterface() const
671 {
672     Q_D(const QNativeSocketEngine);
673     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::multicastInterface(), QNetworkInterface());
674     Q_CHECK_TYPE(QNativeSocketEngine::multicastInterface(), QAbstractSocket::UdpSocket, QNetworkInterface());
675     return d->nativeMulticastInterface();
676 }
677
678 /*! \since 4.8 */
679 bool QNativeSocketEngine::setMulticastInterface(const QNetworkInterface &iface)
680 {
681     Q_D(QNativeSocketEngine);
682     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setMulticastInterface(), false);
683     Q_CHECK_TYPE(QNativeSocketEngine::setMulticastInterface(), QAbstractSocket::UdpSocket, false);
684     return d->nativeSetMulticastInterface(iface);
685 }
686
687 #endif // QT_NO_NETWORKINTERFACE
688
689 /*!
690     Returns the number of bytes that are currently available for
691     reading. On error, -1 is returned.
692
693     For UDP sockets, this function returns the accumulated size of all
694     pending datagrams, and it is therefore more useful for UDP sockets
695     to call hasPendingDatagrams() and pendingDatagramSize().
696 */
697 qint64 QNativeSocketEngine::bytesAvailable() const
698 {
699     Q_D(const QNativeSocketEngine);
700     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::bytesAvailable(), -1);
701     Q_CHECK_NOT_STATE(QNativeSocketEngine::bytesAvailable(), QAbstractSocket::UnconnectedState, false);
702
703     return d->nativeBytesAvailable();
704 }
705
706 /*!
707     Returns true if there is at least one datagram pending. This
708     function is only called by UDP sockets, where a datagram can have
709     a size of 0. TCP sockets call bytesAvailable().
710 */
711 bool QNativeSocketEngine::hasPendingDatagrams() const
712 {
713     Q_D(const QNativeSocketEngine);
714     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::hasPendingDatagrams(), false);
715     Q_CHECK_NOT_STATE(QNativeSocketEngine::hasPendingDatagrams(), QAbstractSocket::UnconnectedState, false);
716     Q_CHECK_TYPE(QNativeSocketEngine::hasPendingDatagrams(), QAbstractSocket::UdpSocket, false);
717
718     return d->nativeHasPendingDatagrams();
719 }
720
721 /*!
722     Returns the size of the pending datagram, or -1 if no datagram is
723     pending. A datagram size of 0 is perfectly valid. This function is
724     called by UDP sockets before receiveMessage(). For TCP sockets,
725     call bytesAvailable().
726 */
727 qint64 QNativeSocketEngine::pendingDatagramSize() const
728 {
729     Q_D(const QNativeSocketEngine);
730     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::pendingDatagramSize(), -1);
731     Q_CHECK_TYPE(QNativeSocketEngine::pendingDatagramSize(), QAbstractSocket::UdpSocket, false);
732
733     return d->nativePendingDatagramSize();
734 }
735
736 /*!
737     Reads up to \a maxSize bytes of a datagram from the socket,
738     stores it in \a data and returns the number of bytes read. The
739     address and port of the sender are stored in \a address and \a
740     port. If either of these pointers is 0, the corresponding value is
741     discarded.
742
743     To avoid unnecessarily loss of data, call pendingDatagramSize() to
744     determine the size of the pending message before reading it. If \a
745     maxSize is too small, the rest of the datagram will be lost.
746
747     Returns -1 if an error occurred.
748
749     \sa hasPendingDatagrams()
750 */
751 qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
752                                       quint16 *port)
753 {
754     Q_D(QNativeSocketEngine);
755     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::readDatagram(), -1);
756     Q_CHECK_TYPE(QNativeSocketEngine::readDatagram(), QAbstractSocket::UdpSocket, false);
757
758     return d->nativeReceiveDatagram(data, maxSize, address, port);
759 }
760
761 /*!
762     Writes a UDP datagram of size \a size bytes to the socket from
763     \a data to the address \a host on port \a port, and returns the
764     number of bytes written, or -1 if an error occurred.
765
766     Only one datagram is sent, and if there is too much data to fit
767     into a single datagram, the operation will fail and error()
768     will return QAbstractSocket::DatagramTooLargeError. Operating systems impose an
769     upper limit to the size of a datagram, but this size is different
770     on almost all platforms. Sending large datagrams is in general
771     disadvised, as even if they are sent successfully, they are likely
772     to be fragmented before arriving at their destination.
773
774     Experience has shown that it is in general safe to send datagrams
775     no larger than 512 bytes.
776
777     \sa readDatagram()
778 */
779 qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 size,
780                                        const QHostAddress &host, quint16 port)
781 {
782     Q_D(QNativeSocketEngine);
783     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::writeDatagram(), -1);
784     Q_CHECK_TYPE(QNativeSocketEngine::writeDatagram(), QAbstractSocket::UdpSocket, -1);
785     return d->nativeSendDatagram(data, size, host, port);
786 }
787
788 /*!
789     Writes a block of \a size bytes from \a data to the socket.
790     Returns the number of bytes written, or -1 if an error occurred.
791 */
792 qint64 QNativeSocketEngine::write(const char *data, qint64 size)
793 {
794     Q_D(QNativeSocketEngine);
795     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::write(), -1);
796     Q_CHECK_STATE(QNativeSocketEngine::write(), QAbstractSocket::ConnectedState, -1);
797     return d->nativeWrite(data, size);
798 }
799
800
801 qint64 QNativeSocketEngine::bytesToWrite() const
802 {
803     return 0;
804 }
805
806 /*!
807     Reads up to \a maxSize bytes into \a data from the socket.
808     Returns the number of bytes read, or -1 if an error occurred.
809 */
810 qint64 QNativeSocketEngine::read(char *data, qint64 maxSize)
811 {
812     Q_D(QNativeSocketEngine);
813     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::read(), -1);
814     Q_CHECK_STATES(QNativeSocketEngine::read(), QAbstractSocket::ConnectedState, QAbstractSocket::BoundState, -1);
815
816     qint64 readBytes = d->nativeRead(data, maxSize);
817
818     // Handle remote close
819     if (readBytes == 0 && d->socketType == QAbstractSocket::TcpSocket) {
820         d->setError(QAbstractSocket::RemoteHostClosedError,
821                     QNativeSocketEnginePrivate::RemoteHostClosedErrorString);
822         close();
823         return -1;
824     } else if (readBytes == -1) {
825         if (!d->hasSetSocketError) {
826             d->hasSetSocketError = true;
827             d->socketError = QAbstractSocket::NetworkError;
828             d->socketErrorString = qt_error_string();
829         }
830         close();
831         return -1;
832     }
833     return readBytes;
834 }
835
836 /*!
837     Closes the socket. In order to use the socket again, initialize()
838     must be called.
839 */
840 void QNativeSocketEngine::close()
841 {
842     Q_D(QNativeSocketEngine);
843     if (d->readNotifier)
844         d->readNotifier->setEnabled(false);
845     if (d->writeNotifier)
846         d->writeNotifier->setEnabled(false);
847     if (d->exceptNotifier)
848         d->exceptNotifier->setEnabled(false);
849
850     if(d->socketDescriptor != -1) {
851         d->nativeClose();
852         d->socketDescriptor = -1;
853     }
854     d->socketState = QAbstractSocket::UnconnectedState;
855     d->hasSetSocketError = false;
856     d->localPort = 0;
857     d->localAddress.clear();
858     d->peerPort = 0;
859     d->peerAddress.clear();
860     if (d->readNotifier) {
861         qDeleteInEventHandler(d->readNotifier);
862         d->readNotifier = 0;
863     }
864     if (d->writeNotifier) {
865         qDeleteInEventHandler(d->writeNotifier);
866         d->writeNotifier = 0;
867     }
868     if (d->exceptNotifier) {
869         qDeleteInEventHandler(d->exceptNotifier);
870         d->exceptNotifier = 0;
871     }
872 }
873
874 /*!
875     Waits for \a msecs milliseconds or until the socket is ready for
876     reading. If \a timedOut is not 0 and \a msecs milliseconds have
877     passed, the value of \a timedOut is set to true.
878
879     Returns true if data is available for reading; otherwise returns
880     false.
881
882     This is a blocking function call; its use is disadvised in a
883     single threaded application, as the whole thread will stop
884     responding until the function returns. waitForRead() is most
885     useful when there is no event loop available. The general approach
886     is to create a QSocketNotifier, passing the socket descriptor
887     returned by socketDescriptor() to its constructor.
888 */
889 bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
890 {
891     Q_D(const QNativeSocketEngine);
892     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForRead(), false);
893     Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForRead(),
894                       QAbstractSocket::UnconnectedState, false);
895
896     if (timedOut)
897         *timedOut = false;
898
899     int ret = d->nativeSelect(msecs, true);
900     if (ret == 0) {
901         if (timedOut)
902             *timedOut = true;
903         d->setError(QAbstractSocket::SocketTimeoutError,
904             QNativeSocketEnginePrivate::TimeOutErrorString);
905         d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
906         return false;
907     } else if (state() == QAbstractSocket::ConnectingState) {
908         connectToHost(d->peerAddress, d->peerPort);
909     }
910
911     return ret > 0;
912 }
913
914 /*!
915     Waits for \a msecs milliseconds or until the socket is ready for
916     writing. If \a timedOut is not 0 and \a msecs milliseconds have
917     passed, the value of \a timedOut is set to true.
918
919     Returns true if data is available for writing; otherwise returns
920     false.
921
922     This is a blocking function call; its use is disadvised in a
923     single threaded application, as the whole thread will stop
924     responding until the function returns. waitForWrite() is most
925     useful when there is no event loop available. The general approach
926     is to create a QSocketNotifier, passing the socket descriptor
927     returned by socketDescriptor() to its constructor.
928 */
929 bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut)
930 {
931     Q_D(QNativeSocketEngine);
932     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForWrite(), false);
933     Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForWrite(),
934                       QAbstractSocket::UnconnectedState, false);
935
936     if (timedOut)
937         *timedOut = false;
938
939     int ret = d->nativeSelect(msecs, false);
940     // On Windows, the socket is in connected state if a call to
941     // select(writable) is successful. In this case we should not
942     // issue a second call to WSAConnect()
943 #if defined (Q_OS_WIN)
944     if (ret > 0) {
945         setState(QAbstractSocket::ConnectedState);
946         d_func()->fetchConnectionParameters();
947         return true;
948     } else {
949         int value = 0;
950         int valueSize = sizeof(value);
951         if (::getsockopt(d->socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
952             if (value == WSAECONNREFUSED) {
953                 d->setError(QAbstractSocket::ConnectionRefusedError, QNativeSocketEnginePrivate::ConnectionRefusedErrorString);
954                 d->socketState = QAbstractSocket::UnconnectedState;
955                 return false;
956             } else if (value == WSAETIMEDOUT) {
957                 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::ConnectionTimeOutErrorString);
958                 d->socketState = QAbstractSocket::UnconnectedState;
959                 return false;
960             } else if (value == WSAEHOSTUNREACH) {
961                 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::HostUnreachableErrorString);
962                 d->socketState = QAbstractSocket::UnconnectedState;
963                 return false;
964             }
965         }
966     }
967 #endif
968
969     if (ret == 0) {
970         if (timedOut)
971             *timedOut = true;
972         d->setError(QAbstractSocket::SocketTimeoutError,
973                     QNativeSocketEnginePrivate::TimeOutErrorString);
974         d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
975         return false;
976     } else if (state() == QAbstractSocket::ConnectingState) {
977         connectToHost(d->peerAddress, d->peerPort);
978     }
979
980     return ret > 0;
981 }
982
983 bool QNativeSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
984                                       bool checkRead, bool checkWrite,
985                                       int msecs, bool *timedOut)
986 {
987     Q_D(QNativeSocketEngine);
988     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForWrite(), false);
989     Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForReadOrWrite(),
990                       QAbstractSocket::UnconnectedState, false);
991
992     int ret = d->nativeSelect(msecs, checkRead, checkWrite, readyToRead, readyToWrite);
993     // On Windows, the socket is in connected state if a call to
994     // select(writable) is successful. In this case we should not
995     // issue a second call to WSAConnect()
996 #if defined (Q_OS_WIN)
997     if (checkWrite && ((readyToWrite && *readyToWrite) || !readyToWrite) && ret > 0) {
998         setState(QAbstractSocket::ConnectedState);
999         d_func()->fetchConnectionParameters();
1000         return true;
1001     } else {
1002         int value = 0;
1003         int valueSize = sizeof(value);
1004         if (::getsockopt(d->socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
1005             if (value == WSAECONNREFUSED) {
1006                 d->setError(QAbstractSocket::ConnectionRefusedError, QNativeSocketEnginePrivate::ConnectionRefusedErrorString);
1007                 d->socketState = QAbstractSocket::UnconnectedState;
1008                 return false;
1009             } else if (value == WSAETIMEDOUT) {
1010                 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::ConnectionTimeOutErrorString);
1011                 d->socketState = QAbstractSocket::UnconnectedState;
1012                 return false;
1013             } else if (value == WSAEHOSTUNREACH) {
1014                 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::HostUnreachableErrorString);
1015                 d->socketState = QAbstractSocket::UnconnectedState;
1016                 return false;
1017             }
1018         }
1019     }
1020 #endif
1021     if (ret == 0) {
1022         if (timedOut)
1023             *timedOut = true;
1024         d->setError(QAbstractSocket::SocketTimeoutError,
1025                     QNativeSocketEnginePrivate::TimeOutErrorString);
1026         d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
1027         return false;
1028     } else if (state() == QAbstractSocket::ConnectingState) {
1029         connectToHost(d->peerAddress, d->peerPort);
1030     }
1031
1032     return ret > 0;
1033 }
1034
1035 /*!
1036     Returns the size of the operating system's socket receive
1037     buffer. Depending on the operating system, this size may be
1038     different from what has been set earlier with
1039     setReceiveBufferSize().
1040 */
1041 qint64 QNativeSocketEngine::receiveBufferSize() const
1042 {
1043     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::receiveBufferSize(), -1);
1044     return option(ReceiveBufferSocketOption);
1045 }
1046
1047 /*!
1048     Sets the size of the operating system receive buffer to \a size.
1049
1050     For clients, this should be set before connectToHost() is called;
1051     otherwise it will have no effect. For servers, it should be called
1052     before listen().
1053
1054     The operating system receive buffer size effectively limits two
1055     things: how much data can be in transit at any one moment, and how
1056     much data can be received in one iteration of the main event loop.
1057     Setting the size of the receive buffer may have an impact on the
1058     socket's performance.
1059
1060     The default value is operating system-dependent.
1061 */
1062 void QNativeSocketEngine::setReceiveBufferSize(qint64 size)
1063 {
1064     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setReceiveBufferSize(), Q_VOID);
1065     setOption(ReceiveBufferSocketOption, size);
1066 }
1067
1068 /*!
1069     Returns the size of the operating system send buffer. Depending on
1070     the operating system, this size may be different from what has
1071     been set earlier with setSendBufferSize().
1072 */
1073 qint64 QNativeSocketEngine::sendBufferSize() const
1074 {
1075     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setSendBufferSize(), -1);
1076     return option(SendBufferSocketOption);
1077 }
1078
1079 /*!
1080     Sets the size of the operating system send buffer to \a size.
1081
1082     The operating system send buffer size effectively limits how much
1083     data can be in transit at any one moment. Setting the size of the
1084     send buffer may have an impact on the socket's performance.
1085
1086     The default value is operating system-dependent.
1087 */
1088 void QNativeSocketEngine::setSendBufferSize(qint64 size)
1089 {
1090     Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setSendBufferSize(), Q_VOID);
1091     setOption(SendBufferSocketOption, size);
1092 }
1093
1094
1095 /*!
1096     Sets the option \a option to the value \a value.
1097 */
1098 bool QNativeSocketEngine::setOption(SocketOption option, int value)
1099 {
1100     Q_D(QNativeSocketEngine);
1101     return d->setOption(option, value);
1102 }
1103
1104 /*!
1105     Returns the value of the option \a socketOption.
1106 */
1107 int QNativeSocketEngine::option(SocketOption socketOption) const
1108 {
1109     Q_D(const QNativeSocketEngine);
1110     return d->option(socketOption);
1111 }
1112
1113 bool QNativeSocketEngine::isReadNotificationEnabled() const
1114 {
1115     Q_D(const QNativeSocketEngine);
1116     return d->readNotifier && d->readNotifier->isEnabled();
1117 }
1118
1119 /*
1120   \internal
1121   \class QReadNotifier
1122   \brief The QReadNotifer class is used to improve performance.
1123
1124   QReadNotifier is a private class used for performance reasons vs
1125   connecting to the QSocketNotifier activated() signal.
1126  */
1127 class QReadNotifier : public QSocketNotifier
1128 {
1129 public:
1130     QReadNotifier(qintptr fd, QNativeSocketEngine *parent)
1131         : QSocketNotifier(fd, QSocketNotifier::Read, parent)
1132     { engine = parent; }
1133
1134 protected:
1135     bool event(QEvent *);
1136
1137     QNativeSocketEngine *engine;
1138 };
1139
1140 bool QReadNotifier::event(QEvent *e)
1141 {
1142     if (e->type() == QEvent::SockAct) {
1143         engine->readNotification();
1144         return true;
1145     }
1146     return QSocketNotifier::event(e);
1147 }
1148
1149 /*
1150   \internal
1151   \class QWriteNotifier
1152   \brief The QWriteNotifer class is used to improve performance.
1153
1154   QWriteNotifier is a private class used for performance reasons vs
1155   connecting to the QSocketNotifier activated() signal.
1156  */
1157 class QWriteNotifier : public QSocketNotifier
1158 {
1159 public:
1160     QWriteNotifier(int fd, QNativeSocketEngine *parent)
1161         : QSocketNotifier(fd, QSocketNotifier::Write, parent) { engine = parent; }
1162
1163 protected:
1164     bool event(QEvent *);
1165
1166     QNativeSocketEngine *engine;
1167 };
1168
1169 bool QWriteNotifier::event(QEvent *e)
1170 {
1171     if (e->type() == QEvent::SockAct) {
1172         if (engine->state() == QAbstractSocket::ConnectingState)
1173             engine->connectionNotification();
1174         else
1175             engine->writeNotification();
1176         return true;
1177     }
1178     return QSocketNotifier::event(e);
1179 }
1180
1181 class QExceptionNotifier : public QSocketNotifier
1182 {
1183 public:
1184     QExceptionNotifier(int fd, QNativeSocketEngine *parent)
1185         : QSocketNotifier(fd, QSocketNotifier::Exception, parent) { engine = parent; }
1186
1187 protected:
1188     bool event(QEvent *);
1189
1190     QNativeSocketEngine *engine;
1191 };
1192
1193 bool QExceptionNotifier::event(QEvent *e)
1194 {
1195     if (e->type() == QEvent::SockAct) {
1196         if (engine->state() == QAbstractSocket::ConnectingState)
1197             engine->connectionNotification();
1198         else
1199             engine->exceptionNotification();
1200         return true;
1201     }
1202     return QSocketNotifier::event(e);
1203 }
1204
1205 void QNativeSocketEngine::setReadNotificationEnabled(bool enable)
1206 {
1207     Q_D(QNativeSocketEngine);
1208     if (d->readNotifier) {
1209         d->readNotifier->setEnabled(enable);
1210     } else if (enable && d->threadData->eventDispatcher) {
1211         d->readNotifier = new QReadNotifier(d->socketDescriptor, this);
1212         d->readNotifier->setEnabled(true);
1213     }
1214 }
1215
1216 bool QNativeSocketEngine::isWriteNotificationEnabled() const
1217 {
1218     Q_D(const QNativeSocketEngine);
1219     return d->writeNotifier && d->writeNotifier->isEnabled();
1220 }
1221
1222 void QNativeSocketEngine::setWriteNotificationEnabled(bool enable)
1223 {
1224     Q_D(QNativeSocketEngine);
1225     if (d->writeNotifier) {
1226         d->writeNotifier->setEnabled(enable);
1227     } else if (enable && d->threadData->eventDispatcher) {
1228         d->writeNotifier = new QWriteNotifier(d->socketDescriptor, this);
1229         d->writeNotifier->setEnabled(true);
1230     }
1231 }
1232
1233 bool QNativeSocketEngine::isExceptionNotificationEnabled() const
1234 {
1235     Q_D(const QNativeSocketEngine);
1236     return d->exceptNotifier && d->exceptNotifier->isEnabled();
1237 }
1238
1239 void QNativeSocketEngine::setExceptionNotificationEnabled(bool enable)
1240 {
1241     Q_D(QNativeSocketEngine);
1242     if (d->exceptNotifier) {
1243         d->exceptNotifier->setEnabled(enable);
1244     } else if (enable && d->threadData->eventDispatcher) {
1245         d->exceptNotifier = new QExceptionNotifier(d->socketDescriptor, this);
1246         d->exceptNotifier->setEnabled(true);
1247     }
1248 }
1249
1250 QT_END_NAMESPACE