Warning: That file was not part of the compilation database. It may have many parsing errors.

1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Copyright (C) 2016 Intel Corporation.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41// Prevent windows system header files from defining min/max as macros.
42#define NOMINMAX 1
43
44#include <winsock2.h>
45#include <ws2tcpip.h>
46
47#include "qnativesocketengine_p.h"
48
49#include <qabstracteventdispatcher.h>
50#include <qsocketnotifier.h>
51#include <qdebug.h>
52#include <qdatetime.h>
53#include <qnetworkinterface.h>
54#include <qoperatingsystemversion.h>
55
56//#define QNATIVESOCKETENGINE_DEBUG
57#if defined(QNATIVESOCKETENGINE_DEBUG)
58# include <qstring.h>
59# include <qbytearray.h>
60#endif
61
62QT_BEGIN_NAMESPACE
63
64//Some distributions of mingw (including 4.7.2 from mingw.org) are missing this from headers.
65//Also microsoft headers don't include it when building on XP and earlier.
66#ifndef IPV6_V6ONLY
67#define IPV6_V6ONLY 27
68#endif
69#ifndef IP_HOPLIMIT
70#define IP_HOPLIMIT 21 // Receive packet hop limit.
71#endif
72
73#if defined(QNATIVESOCKETENGINE_DEBUG)
74
75void verboseWSErrorDebug(int r)
76{
77 switch (r) {
78 case WSANOTINITIALISED : qDebug("WSA error : WSANOTINITIALISED"); break;
79 case WSAEINTR: qDebug("WSA error : WSAEINTR"); break;
80 case WSAEBADF: qDebug("WSA error : WSAEBADF"); break;
81 case WSAEACCES: qDebug("WSA error : WSAEACCES"); break;
82 case WSAEFAULT: qDebug("WSA error : WSAEFAULT"); break;
83 case WSAEINVAL: qDebug("WSA error : WSAEINVAL"); break;
84 case WSAEMFILE: qDebug("WSA error : WSAEMFILE"); break;
85 case WSAEWOULDBLOCK: qDebug("WSA error : WSAEWOULDBLOCK"); break;
86 case WSAEINPROGRESS: qDebug("WSA error : WSAEINPROGRESS"); break;
87 case WSAEALREADY: qDebug("WSA error : WSAEALREADY"); break;
88 case WSAENOTSOCK: qDebug("WSA error : WSAENOTSOCK"); break;
89 case WSAEDESTADDRREQ: qDebug("WSA error : WSAEDESTADDRREQ"); break;
90 case WSAEMSGSIZE: qDebug("WSA error : WSAEMSGSIZE"); break;
91 case WSAEPROTOTYPE: qDebug("WSA error : WSAEPROTOTYPE"); break;
92 case WSAENOPROTOOPT: qDebug("WSA error : WSAENOPROTOOPT"); break;
93 case WSAEPROTONOSUPPORT: qDebug("WSA error : WSAEPROTONOSUPPORT"); break;
94 case WSAESOCKTNOSUPPORT: qDebug("WSA error : WSAESOCKTNOSUPPORT"); break;
95 case WSAEOPNOTSUPP: qDebug("WSA error : WSAEOPNOTSUPP"); break;
96 case WSAEPFNOSUPPORT: qDebug("WSA error : WSAEPFNOSUPPORT"); break;
97 case WSAEAFNOSUPPORT: qDebug("WSA error : WSAEAFNOSUPPORT"); break;
98 case WSAEADDRINUSE: qDebug("WSA error : WSAEADDRINUSE"); break;
99 case WSAEADDRNOTAVAIL: qDebug("WSA error : WSAEADDRNOTAVAIL"); break;
100 case WSAENETDOWN: qDebug("WSA error : WSAENETDOWN"); break;
101 case WSAENETUNREACH: qDebug("WSA error : WSAENETUNREACH"); break;
102 case WSAENETRESET: qDebug("WSA error : WSAENETRESET"); break;
103 case WSAECONNABORTED: qDebug("WSA error : WSAECONNABORTED"); break;
104 case WSAECONNRESET: qDebug("WSA error : WSAECONNRESET"); break;
105 case WSAENOBUFS: qDebug("WSA error : WSAENOBUFS"); break;
106 case WSAEISCONN: qDebug("WSA error : WSAEISCONN"); break;
107 case WSAENOTCONN: qDebug("WSA error : WSAENOTCONN"); break;
108 case WSAESHUTDOWN: qDebug("WSA error : WSAESHUTDOWN"); break;
109 case WSAETOOMANYREFS: qDebug("WSA error : WSAETOOMANYREFS"); break;
110 case WSAETIMEDOUT: qDebug("WSA error : WSAETIMEDOUT"); break;
111 case WSAECONNREFUSED: qDebug("WSA error : WSAECONNREFUSED"); break;
112 case WSAELOOP: qDebug("WSA error : WSAELOOP"); break;
113 case WSAENAMETOOLONG: qDebug("WSA error : WSAENAMETOOLONG"); break;
114 case WSAEHOSTDOWN: qDebug("WSA error : WSAEHOSTDOWN"); break;
115 case WSAEHOSTUNREACH: qDebug("WSA error : WSAEHOSTUNREACH"); break;
116 case WSAENOTEMPTY: qDebug("WSA error : WSAENOTEMPTY"); break;
117 case WSAEPROCLIM: qDebug("WSA error : WSAEPROCLIM"); break;
118 case WSAEUSERS: qDebug("WSA error : WSAEUSERS"); break;
119 case WSAEDQUOT: qDebug("WSA error : WSAEDQUOT"); break;
120 case WSAESTALE: qDebug("WSA error : WSAESTALE"); break;
121 case WSAEREMOTE: qDebug("WSA error : WSAEREMOTE"); break;
122 case WSAEDISCON: qDebug("WSA error : WSAEDISCON"); break;
123 default: qDebug("WSA error : Unknown"); break;
124 }
125 qErrnoWarning(r, "more details");
126}
127
128/*
129 Returns a human readable representation of the first \a len
130 characters in \a data.
131*/
132static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
133{
134 if (!data) return "(null)";
135 QByteArray out;
136 for (int i = 0; i < len; ++i) {
137 char c = data[i];
138 if (isprint(int(uchar(c)))) {
139 out += c;
140 } else switch (c) {
141 case '\n': out += "\\n"; break;
142 case '\r': out += "\\r"; break;
143 case '\t': out += "\\t"; break;
144 default:
145 QString tmp;
146 tmp.sprintf("\\%o", c);
147 out += tmp.toLatin1().constData();
148 }
149 }
150
151 if (len < maxLength)
152 out += "...";
153
154 return out;
155}
156
157
158#define WS_ERROR_DEBUG(x) verboseWSErrorDebug(x);
159
160#else
161
162#define WS_ERROR_DEBUG(x) Q_UNUSED(x)
163
164#endif
165
166#ifndef AF_INET6
167#define AF_INET6 23 /* Internetwork Version 6 */
168#endif
169
170#ifndef SO_EXCLUSIVEADDRUSE
171#define SO_EXCLUSIVEADDRUSE ((int)(~SO_REUSEADDR)) /* disallow local address reuse */
172#endif
173
174/*
175 Extracts the port and address from a sockaddr, and stores them in
176 \a port and \a addr if they are non-null.
177*/
178static inline void qt_socket_getPortAndAddress(SOCKET socketDescriptor, const qt_sockaddr *sa, quint16 *port, QHostAddress *address)
179{
180 if (sa->a.sa_family == AF_INET6) {
181 const sockaddr_in6 *sa6 = &sa->a6;
182 Q_IPV6ADDR tmp;
183 for (int i = 0; i < 16; ++i)
184 tmp.c[i] = sa6->sin6_addr.s6_addr[i];
185 if (address) {
186 QHostAddress a;
187 a.setAddress(tmp);
188 if (sa6->sin6_scope_id)
189 a.setScopeId(QString::number(sa6->sin6_scope_id));
190 *address = a;
191 }
192 if (port)
193 WSANtohs(socketDescriptor, sa6->sin6_port, port);
194 } else
195
196 if (sa->a.sa_family == AF_INET) {
197 const sockaddr_in *sa4 = &sa->a4;
198 unsigned long addr;
199 WSANtohl(socketDescriptor, sa4->sin_addr.s_addr, &addr);
200 QHostAddress a;
201 a.setAddress(addr);
202 if (address)
203 *address = a;
204 if (port)
205 WSANtohs(socketDescriptor, sa4->sin_port, port);
206 }
207}
208
209static void convertToLevelAndOption(QNativeSocketEngine::SocketOption opt,
210 QAbstractSocket::NetworkLayerProtocol socketProtocol, int &level, int &n)
211{
212 n = -1;
213 level = SOL_SOCKET; // default
214
215 switch (opt) {
216 case QNativeSocketEngine::NonBlockingSocketOption: // WSAIoctl
217 case QNativeSocketEngine::TypeOfServiceOption: // not supported
218 case QNativeSocketEngine::MaxStreamsSocketOption:
219 Q_UNREACHABLE();
220
221 case QNativeSocketEngine::ReceiveBufferSocketOption:
222 n = SO_RCVBUF;
223 break;
224 case QNativeSocketEngine::SendBufferSocketOption:
225 n = SO_SNDBUF;
226 break;
227 case QNativeSocketEngine::BroadcastSocketOption:
228 n = SO_BROADCAST;
229 break;
230 case QNativeSocketEngine::AddressReusable:
231 n = SO_REUSEADDR;
232 break;
233 case QNativeSocketEngine::BindExclusively:
234 n = SO_EXCLUSIVEADDRUSE;
235 break;
236 case QNativeSocketEngine::ReceiveOutOfBandData:
237 n = SO_OOBINLINE;
238 break;
239 case QNativeSocketEngine::LowDelayOption:
240 level = IPPROTO_TCP;
241 n = TCP_NODELAY;
242 break;
243 case QNativeSocketEngine::KeepAliveOption:
244 n = SO_KEEPALIVE;
245 break;
246 case QNativeSocketEngine::MulticastTtlOption:
247 if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
248 level = IPPROTO_IPV6;
249 n = IPV6_MULTICAST_HOPS;
250 } else
251 {
252 level = IPPROTO_IP;
253 n = IP_MULTICAST_TTL;
254 }
255 break;
256 case QNativeSocketEngine::MulticastLoopbackOption:
257 if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
258 level = IPPROTO_IPV6;
259 n = IPV6_MULTICAST_LOOP;
260 } else
261 {
262 level = IPPROTO_IP;
263 n = IP_MULTICAST_LOOP;
264 }
265 break;
266 case QNativeSocketEngine::ReceivePacketInformation:
267 if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
268 level = IPPROTO_IPV6;
269 n = IPV6_PKTINFO;
270 } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
271 level = IPPROTO_IP;
272 n = IP_PKTINFO;
273 }
274 break;
275 case QNativeSocketEngine::ReceiveHopLimit:
276 if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
277 level = IPPROTO_IPV6;
278 n = IPV6_HOPLIMIT;
279 } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
280 level = IPPROTO_IP;
281 n = IP_HOPLIMIT;
282 }
283 break;
284
285 case QAbstractSocketEngine::PathMtuInformation:
286 break; // not supported on Windows
287 }
288}
289
290/*! \internal
291
292*/
293static inline QAbstractSocket::SocketType qt_socket_getType(qintptr socketDescriptor)
294{
295 int value = 0;
296 QT_SOCKLEN_T valueSize = sizeof(value);
297 if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_TYPE,
298 reinterpret_cast<char *>(&value), &valueSize) != 0) {
299 WS_ERROR_DEBUG(WSAGetLastError());
300 } else {
301 if (value == SOCK_STREAM)
302 return QAbstractSocket::TcpSocket;
303 else if (value == SOCK_DGRAM)
304 return QAbstractSocket::UdpSocket;
305 }
306 return QAbstractSocket::UnknownSocketType;
307}
308
309// MS Transport Provider IOCTL to control
310// reporting PORT_UNREACHABLE messages
311// on UDP sockets via recv/WSARecv/etc.
312// Path TRUE in input buffer to enable (default if supported),
313// FALSE to disable.
314#ifndef SIO_UDP_CONNRESET
315# ifndef IOC_VENDOR
316# define IOC_VENDOR 0x18000000
317# endif
318# ifndef _WSAIOW
319# define _WSAIOW(x,y) (IOC_IN|(x)|(y))
320# endif
321# define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
322#endif
323
324bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
325{
326
327 //### no ip6 support on winsocket 1.1 but we will try not to use this !!!!!!!!!!!!1
328 /*
329 if (winsockVersion < 0x20 && socketProtocol == QAbstractSocket::IPv6Protocol) {
330 //### no ip6 support
331 return -1;
332 }
333 */
334
335 //### SCTP not implemented
336 if (socketType == QAbstractSocket::SctpSocket) {
337 setError(QAbstractSocket::UnsupportedSocketOperationError,
338 ProtocolUnsupportedErrorString);
339 return false;
340 }
341
342 //Windows XP and 2003 support IPv6 but not dual stack sockets
343 int protocol = (socketProtocol == QAbstractSocket::IPv6Protocol
344 || (socketProtocol == QAbstractSocket::AnyIPProtocol)) ? AF_INET6 : AF_INET;
345 int type = (socketType == QAbstractSocket::UdpSocket) ? SOCK_DGRAM : SOCK_STREAM;
346
347 // MSDN KB179942 states that on winnt 4 WSA_FLAG_OVERLAPPED is needed if socket is to be non blocking
348 // and recomends alwasy doing it for cross windows version comapablity.
349
350 // WSA_FLAG_NO_HANDLE_INHERIT is atomic (like linux O_CLOEXEC), but requires windows 7 SP 1 or later
351 // SetHandleInformation is supported since W2K but isn't atomic
352#ifndef WSA_FLAG_NO_HANDLE_INHERIT
353#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
354#endif
355
356 SOCKET socket = ::WSASocket(protocol, type, 0, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
357 // previous call fails if the windows 7 service pack 1 or hot fix isn't installed.
358
359 // Try the old API if the new one failed on Windows 7
360 if (socket == INVALID_SOCKET && QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows8) {
361 socket = ::WSASocket(protocol, type, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
362#ifdef HANDLE_FLAG_INHERIT
363 if (socket != INVALID_SOCKET) {
364 // make non inheritable the old way
365 BOOL handleFlags = SetHandleInformation(reinterpret_cast<HANDLE>(socket), HANDLE_FLAG_INHERIT, 0);
366#ifdef QNATIVESOCKETENGINE_DEBUG
367 qDebug() << "QNativeSocketEnginePrivate::createNewSocket - set inheritable" << handleFlags;
368#else
369 Q_UNUSED(handleFlags);
370#endif
371 }
372#endif
373 }
374
375 if (socket == INVALID_SOCKET) {
376 int err = WSAGetLastError();
377 WS_ERROR_DEBUG(err);
378 switch (err) {
379 case WSANOTINITIALISED:
380 //###
381 break;
382 case WSAEAFNOSUPPORT:
383 case WSAESOCKTNOSUPPORT:
384 case WSAEPROTOTYPE:
385 case WSAEINVAL:
386 setError(QAbstractSocket::UnsupportedSocketOperationError, ProtocolUnsupportedErrorString);
387 break;
388 case WSAEMFILE:
389 case WSAENOBUFS:
390 setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
391 break;
392 default:
393 break;
394 }
395
396 return false;
397 }
398
399 if (socketType == QAbstractSocket::UdpSocket) {
400 // enable new behavior using
401 // SIO_UDP_CONNRESET
402 DWORD dwBytesReturned = 0;
403 int bNewBehavior = 1;
404 if (::WSAIoctl(socket, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior),
405 NULL, 0, &dwBytesReturned, NULL, NULL) == SOCKET_ERROR) {
406 // not to worry isBogusUdpReadNotification() should handle this otherwise
407 int err = WSAGetLastError();
408 WS_ERROR_DEBUG(err);
409 }
410 }
411
412 // get the pointer to sendmsg and recvmsg
413 DWORD bytesReturned;
414 GUID recvmsgguid = WSAID_WSARECVMSG;
415 if (WSAIoctl(socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
416 &recvmsgguid, sizeof(recvmsgguid),
417 &recvmsg, sizeof(recvmsg), &bytesReturned, NULL, NULL) == SOCKET_ERROR)
418 recvmsg = 0;
419
420 GUID sendmsgguid = WSAID_WSASENDMSG;
421 if (WSAIoctl(socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
422 &sendmsgguid, sizeof(sendmsgguid),
423 &sendmsg, sizeof(sendmsg), &bytesReturned, NULL, NULL) == SOCKET_ERROR)
424 sendmsg = 0;
425
426 socketDescriptor = socket;
427 if (socket != INVALID_SOCKET) {
428 this->socketProtocol = socketProtocol;
429 this->socketType = socketType;
430 }
431
432 // Make the socket nonblocking.
433 if (!setOption(QAbstractSocketEngine::NonBlockingSocketOption, 1)) {
434 setError(QAbstractSocket::UnsupportedSocketOperationError, NonBlockingInitFailedErrorString);
435 q_func()->close();
436 return false;
437 }
438
439 return true;
440}
441
442/*! \internal
443
444 Returns the value of the socket option \a opt.
445*/
446int QNativeSocketEnginePrivate::option(QNativeSocketEngine::SocketOption opt) const
447{
448 Q_Q(const QNativeSocketEngine);
449 if (!q->isValid())
450 return -1;
451
452 // handle non-getsockopt
453 switch (opt) {
454 case QNativeSocketEngine::NonBlockingSocketOption: {
455 unsigned long buf = 0;
456 if (WSAIoctl(socketDescriptor, FIONBIO, 0,0, &buf, sizeof(buf), 0,0,0) == 0)
457 return buf;
458 else
459 return -1;
460 break;
461 }
462 case QNativeSocketEngine::TypeOfServiceOption:
463 case QNativeSocketEngine::MaxStreamsSocketOption:
464 return -1;
465
466 default:
467 break;
468 }
469
470#if Q_BYTE_ORDER != Q_LITTLE_ENDIAN
471#error code assumes windows is little endian
472#endif
473 int n, level;
474 int v = 0; //note: windows doesn't write to all bytes if the option type is smaller than int
475 QT_SOCKOPTLEN_T len = sizeof(v);
476
477 convertToLevelAndOption(opt, socketProtocol, level, n);
478 if (n != -1) {
479 if (getsockopt(socketDescriptor, level, n, (char *) &v, &len) == 0)
480 return v;
481 WS_ERROR_DEBUG(WSAGetLastError());
482 }
483 return -1;
484}
485
486
487/*! \internal
488 Sets the socket option \a opt to \a v.
489*/
490bool QNativeSocketEnginePrivate::setOption(QNativeSocketEngine::SocketOption opt, int v)
491{
492 Q_Q(const QNativeSocketEngine);
493 if (!q->isValid())
494 return false;
495
496 // handle non-setsockopt options
497 switch (opt) {
498 case QNativeSocketEngine::SendBufferSocketOption:
499 // see QTBUG-30478 SO_SNDBUF should not be used on Vista or later
500 return false;
501 case QNativeSocketEngine::NonBlockingSocketOption:
502 {
503 unsigned long buf = v;
504 unsigned long outBuf;
505 DWORD sizeWritten = 0;
506 if (::WSAIoctl(socketDescriptor, FIONBIO, &buf, sizeof(unsigned long), &outBuf, sizeof(unsigned long), &sizeWritten, 0,0) == SOCKET_ERROR) {
507 WS_ERROR_DEBUG(WSAGetLastError());
508 return false;
509 }
510 return true;
511 break;
512 }
513 case QNativeSocketEngine::TypeOfServiceOption:
514 case QNativeSocketEngine::MaxStreamsSocketOption:
515 return false;
516
517 default:
518 break;
519 }
520
521 int n, level;
522 convertToLevelAndOption(opt, socketProtocol, level, n);
523 if (n == -1)
524 return false;
525 if (::setsockopt(socketDescriptor, level, n, (char*)&v, sizeof(v)) != 0) {
526 WS_ERROR_DEBUG(WSAGetLastError());
527 return false;
528 }
529 return true;
530}
531
532/*!
533 Fetches information about both ends of the connection: whatever is
534 available.
535*/
536bool QNativeSocketEnginePrivate::fetchConnectionParameters()
537{
538 localPort = 0;
539 localAddress.clear();
540 peerPort = 0;
541 peerAddress.clear();
542 inboundStreamCount = outboundStreamCount = 0;
543
544 if (socketDescriptor == -1)
545 return false;
546
547 qt_sockaddr sa;
548 QT_SOCKLEN_T sockAddrSize = sizeof(sa);
549
550 // Determine local address
551 memset(&sa, 0, sizeof(sa));
552 if (::getsockname(socketDescriptor, &sa.a, &sockAddrSize) == 0) {
553 qt_socket_getPortAndAddress(socketDescriptor, &sa, &localPort, &localAddress);
554 // Determine protocol family
555 switch (sa.a.sa_family) {
556 case AF_INET:
557 socketProtocol = QAbstractSocket::IPv4Protocol;
558 break;
559 case AF_INET6:
560 socketProtocol = QAbstractSocket::IPv6Protocol;
561 break;
562 default:
563 socketProtocol = QAbstractSocket::UnknownNetworkLayerProtocol;
564 break;
565 }
566 } else {
567 int err = WSAGetLastError();
568 WS_ERROR_DEBUG(err);
569 if (err == WSAENOTSOCK) {
570 setError(QAbstractSocket::UnsupportedSocketOperationError,
571 InvalidSocketErrorString);
572 return false;
573 }
574 }
575
576 // determine if local address is dual mode
577 DWORD ipv6only = 0;
578 QT_SOCKOPTLEN_T optlen = sizeof(ipv6only);
579 if (localAddress == QHostAddress::AnyIPv6
580 && !getsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, &optlen )) {
581 if (!ipv6only) {
582 socketProtocol = QAbstractSocket::AnyIPProtocol;
583 localAddress = QHostAddress::Any;
584 }
585 }
586
587 // Some Windows kernels return a v4-mapped QHostAddress::AnyIPv4 as a
588 // local address of the socket which bound on both IPv4 and IPv6 interfaces.
589 // This address does not match to any special address and should not be used
590 // to send the data. So, replace it with QHostAddress::Any.
591 if (socketProtocol == QAbstractSocket::IPv6Protocol) {
592 bool ok = false;
593 const quint32 localIPv4 = localAddress.toIPv4Address(&ok);
594 if (ok && localIPv4 == INADDR_ANY) {
595 socketProtocol = QAbstractSocket::AnyIPProtocol;
596 localAddress = QHostAddress::Any;
597 }
598 }
599
600 memset(&sa, 0, sizeof(sa));
601 if (::getpeername(socketDescriptor, &sa.a, &sockAddrSize) == 0) {
602 qt_socket_getPortAndAddress(socketDescriptor, &sa, &peerPort, &peerAddress);
603 inboundStreamCount = outboundStreamCount = 1;
604 } else {
605 WS_ERROR_DEBUG(WSAGetLastError());
606 }
607
608 socketType = qt_socket_getType(socketDescriptor);
609
610#if defined (QNATIVESOCKETENGINE_DEBUG)
611 QString socketProtocolStr = QStringLiteral("UnknownProtocol");
612 if (socketProtocol == QAbstractSocket::IPv4Protocol) socketProtocolStr = QStringLiteral("IPv4Protocol");
613 else if (socketProtocol == QAbstractSocket::IPv6Protocol) socketProtocolStr = QStringLiteral("IPv6Protocol");
614
615 QString socketTypeStr = QStringLiteral("UnknownSocketType");
616 if (socketType == QAbstractSocket::TcpSocket) socketTypeStr = QStringLiteral("TcpSocket");
617 else if (socketType == QAbstractSocket::UdpSocket) socketTypeStr = QStringLiteral("UdpSocket");
618
619 qDebug("QNativeSocketEnginePrivate::fetchConnectionParameters() localAddress == %s, localPort = %i, peerAddress == %s, peerPort = %i, socketProtocol == %s, socketType == %s", localAddress.toString().toLatin1().constData(), localPort, peerAddress.toString().toLatin1().constData(), peerPort, socketProtocolStr.toLatin1().constData(), socketTypeStr.toLatin1().constData());
620#endif
621
622 return true;
623}
624
625
626static void setErrorFromWSAError(int error, QNativeSocketEnginePrivate *d)
627{
628 Q_ASSERT(d);
629 switch (error) {
630 case WSAEISCONN:
631 d->socketState = QAbstractSocket::ConnectedState;
632 break;
633 case WSAEHOSTUNREACH:
634 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::HostUnreachableErrorString);
635 d->socketState = QAbstractSocket::UnconnectedState;
636 break;
637 case WSAEADDRNOTAVAIL:
638 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::AddressNotAvailableErrorString);
639 d->socketState = QAbstractSocket::UnconnectedState;
640 break;
641 case WSAEINPROGRESS:
642 d->setError(QAbstractSocket::UnfinishedSocketOperationError, QNativeSocketEnginePrivate::InvalidSocketErrorString);
643 d->socketState = QAbstractSocket::ConnectingState;
644 break;
645 case WSAEADDRINUSE:
646 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::AddressInuseErrorString);
647 break;
648 case WSAECONNREFUSED:
649 d->setError(QAbstractSocket::ConnectionRefusedError, QNativeSocketEnginePrivate::ConnectionRefusedErrorString);
650 d->socketState = QAbstractSocket::UnconnectedState;
651 break;
652 case WSAETIMEDOUT:
653 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::ConnectionTimeOutErrorString);
654 d->socketState = QAbstractSocket::UnconnectedState;
655 break;
656 case WSAEACCES:
657 d->setError(QAbstractSocket::SocketAccessError, QNativeSocketEnginePrivate::AccessErrorString);
658 d->socketState = QAbstractSocket::UnconnectedState;
659 break;
660 case WSAENETUNREACH:
661 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::NetworkUnreachableErrorString);
662 d->socketState = QAbstractSocket::UnconnectedState;
663 break;
664 case WSAEINVAL:
665 case WSAEALREADY:
666 d->setError(QAbstractSocket::UnfinishedSocketOperationError, QNativeSocketEnginePrivate::InvalidSocketErrorString);
667 break;
668 default:
669 break;
670 }
671}
672
673bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quint16 port)
674{
675
676#if defined (QNATIVESOCKETENGINE_DEBUG)
677 qDebug("QNativeSocketEnginePrivate::nativeConnect() to %s :: %i", address.toString().toLatin1().constData(), port);
678#endif
679
680 qt_sockaddr aa;
681 QT_SOCKLEN_T sockAddrSize = 0;
682
683 setPortAndAddress(port, address, &aa, &sockAddrSize);
684
685 if ((socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) && address.toIPv4Address()) {
686 //IPV6_V6ONLY option must be cleared to connect to a V4 mapped address
687 DWORD ipv6only = 0;
688 ipv6only = ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
689 }
690
691 forever {
692 int connectResult = ::WSAConnect(socketDescriptor, &aa.a, sockAddrSize, 0,0,0,0);
693 if (connectResult == SOCKET_ERROR) {
694 int err = WSAGetLastError();
695 WS_ERROR_DEBUG(err);
696
697 switch (err) {
698 case WSANOTINITIALISED:
699 //###
700 break;
701 case WSAEWOULDBLOCK: {
702 // If WSAConnect returns WSAEWOULDBLOCK on the second
703 // connection attempt, we have to check SO_ERROR's
704 // value to detect ECONNREFUSED. If we don't get
705 // ECONNREFUSED, we'll have to treat it as an
706 // unfinished operation.
707 int value = 0;
708 QT_SOCKLEN_T valueSize = sizeof(value);
709 bool tryAgain = false;
710 bool errorDetected = false;
711 int tries = 0;
712 do {
713 if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
714 if (value != NOERROR) {
715 WS_ERROR_DEBUG(value);
716 errorDetected = true;
717 // MSDN says getsockopt with SO_ERROR clears the error, but it's not actually cleared
718 // and this can affect all subsequent WSAConnect attempts, so clear it now.
719 const int val = NO_ERROR;
720 ::setsockopt(socketDescriptor, SOL_SOCKET, SO_ERROR, reinterpret_cast<const char*>(&val), sizeof val);
721 } else {
722 // When we get WSAEWOULDBLOCK the outcome was not known, so a
723 // NOERROR might indicate that the result of the operation
724 // is still unknown. We try again to increase the chance that we did
725 // get the correct result.
726 tryAgain = !tryAgain;
727 }
728 setErrorFromWSAError(value, this);
729 }
730 tries++;
731 } while (tryAgain && (tries < 2));
732
733 if (errorDetected)
734 break;
735 // fall through to unfinished operation error handling
736 err = WSAEINPROGRESS;
737 Q_FALLTHROUGH();
738 }
739
740 default:
741 setErrorFromWSAError(err, this);
742 break;
743 }
744 if (socketState != QAbstractSocket::ConnectedState) {
745#if defined (QNATIVESOCKETENGINE_DEBUG)
746 qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
747 address.toString().toLatin1().constData(), port,
748 socketState == QAbstractSocket::ConnectingState
749 ? "Connection in progress" : socketErrorString.toLatin1().constData());
750#endif
751 return false;
752 }
753 }
754 break;
755 }
756
757#if defined (QNATIVESOCKETENGINE_DEBUG)
758 qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == true",
759 address.toString().toLatin1().constData(), port);
760#endif
761
762 socketState = QAbstractSocket::ConnectedState;
763 return true;
764}
765
766
767bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &a, quint16 port)
768{
769 QHostAddress address = a;
770 if (address.protocol() == QAbstractSocket::IPv4Protocol) {
771 if ((address.toIPv4Address() & 0xffff0000) == 0xefff0000) {
772 // binding to a multicast address
773 address = QHostAddress(QHostAddress::AnyIPv4);
774 }
775 }
776
777 qt_sockaddr aa;
778 QT_SOCKLEN_T sockAddrSize = 0;
779 setPortAndAddress(port, address, &aa, &sockAddrSize);
780
781 if (aa.a.sa_family == AF_INET6) {
782 // The default may change in future, so set it explicitly
783 int ipv6only = 0;
784 if (address.protocol() == QAbstractSocket::IPv6Protocol)
785 ipv6only = 1;
786 ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
787 }
788
789
790 int bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);
791 if (bindResult == SOCKET_ERROR && WSAGetLastError() == WSAEAFNOSUPPORT
792 && address.protocol() == QAbstractSocket::AnyIPProtocol) {
793 // retry with v4
794 aa.a4.sin_family = AF_INET;
795 aa.a4.sin_port = htons(port);
796 aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());
797 sockAddrSize = sizeof(aa.a4);
798 bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);
799 }
800 if (bindResult == SOCKET_ERROR) {
801 int err = WSAGetLastError();
802 WS_ERROR_DEBUG(err);
803 switch (err) {
804 case WSANOTINITIALISED:
805 //###
806 break;
807 case WSAEADDRINUSE:
808 case WSAEINVAL:
809 setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
810 break;
811 case WSAEACCES:
812 setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);
813 break;
814 case WSAEADDRNOTAVAIL:
815 setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);
816 break;
817 default:
818 break;
819 }
820
821#if defined (QNATIVESOCKETENGINE_DEBUG)
822 qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
823 address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
824#endif
825
826 return false;
827 }
828
829#if defined (QNATIVESOCKETENGINE_DEBUG)
830 qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == true",
831 address.toString().toLatin1().constData(), port);
832#endif
833 socketState = QAbstractSocket::BoundState;
834 return true;
835}
836
837
838bool QNativeSocketEnginePrivate::nativeListen(int backlog)
839{
840 if (::listen(socketDescriptor, backlog) == SOCKET_ERROR) {
841 int err = WSAGetLastError();
842 WS_ERROR_DEBUG(err);
843 switch (err) {
844 case WSANOTINITIALISED:
845 //###
846 break;
847 case WSAEADDRINUSE:
848 setError(QAbstractSocket::AddressInUseError,
849 PortInuseErrorString);
850 break;
851 default:
852 break;
853 }
854
855#if defined (QNATIVESOCKETENGINE_DEBUG)
856 qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == false (%s)",
857 backlog, socketErrorString.toLatin1().constData());
858#endif
859 return false;
860 }
861
862#if defined (QNATIVESOCKETENGINE_DEBUG)
863 qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == true", backlog);
864#endif
865
866 socketState = QAbstractSocket::ListeningState;
867 return true;
868}
869
870int QNativeSocketEnginePrivate::nativeAccept()
871{
872 int acceptedDescriptor = WSAAccept(socketDescriptor, 0,0,0,0);
873 if (acceptedDescriptor == -1) {
874 int err = WSAGetLastError();
875 switch (err) {
876 case WSAEACCES:
877 setError(QAbstractSocket::SocketAccessError, AccessErrorString);
878 break;
879 case WSAECONNREFUSED:
880 setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
881 break;
882 case WSAECONNRESET:
883 setError(QAbstractSocket::NetworkError, RemoteHostClosedErrorString);
884 break;
885 case WSAENETDOWN:
886 setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
887 break;
888 case WSAENOTSOCK:
889 setError(QAbstractSocket::SocketResourceError, NotSocketErrorString);
890 break;
891 case WSAEINVAL:
892 case WSAEOPNOTSUPP:
893 setError(QAbstractSocket::UnsupportedSocketOperationError, ProtocolUnsupportedErrorString);
894 break;
895 case WSAEFAULT:
896 case WSAEMFILE:
897 case WSAENOBUFS:
898 setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
899 break;
900 case WSAEWOULDBLOCK:
901 setError(QAbstractSocket::TemporaryError, TemporaryErrorString);
902 break;
903 default:
904 setError(QAbstractSocket::UnknownSocketError, UnknownSocketErrorString);
905 break;
906 }
907 } else if (acceptedDescriptor != -1 && QAbstractEventDispatcher::instance()) {
908 // Because of WSAAsyncSelect() WSAAccept returns a non blocking socket
909 // with the same attributes as the listening socket including the current
910 // WSAAsyncSelect(). To be able to change the socket to blocking mode the
911 // WSAAsyncSelect() call must be cancled.
912 QSocketNotifier n(acceptedDescriptor, QSocketNotifier::Read);
913 n.setEnabled(true);
914 n.setEnabled(false);
915 }
916#if defined (QNATIVESOCKETENGINE_DEBUG)
917 qDebug("QNativeSocketEnginePrivate::nativeAccept() == %i", acceptedDescriptor);
918#endif
919 return acceptedDescriptor;
920}
921
922static bool multicastMembershipHelper(QNativeSocketEnginePrivate *d,
923 int how6,
924 int how4,
925 const QHostAddress &groupAddress,
926 const QNetworkInterface &iface)
927{
928 int level = 0;
929 int sockOpt = 0;
930 char *sockArg;
931 int sockArgSize;
932
933 struct ip_mreq mreq4;
934 struct ipv6_mreq mreq6;
935
936 if (groupAddress.protocol() == QAbstractSocket::IPv6Protocol) {
937 level = IPPROTO_IPV6;
938 sockOpt = how6;
939 sockArg = reinterpret_cast<char *>(&mreq6);
940 sockArgSize = sizeof(mreq6);
941 memset(&mreq6, 0, sizeof(mreq6));
942 Q_IPV6ADDR ip6 = groupAddress.toIPv6Address();
943 memcpy(&mreq6.ipv6mr_multiaddr, &ip6, sizeof(ip6));
944 mreq6.ipv6mr_interface = iface.index();
945 } else if (groupAddress.protocol() == QAbstractSocket::IPv4Protocol) {
946 level = IPPROTO_IP;
947 sockOpt = how4;
948 sockArg = reinterpret_cast<char *>(&mreq4);
949 sockArgSize = sizeof(mreq4);
950 memset(&mreq4, 0, sizeof(mreq4));
951 mreq4.imr_multiaddr.s_addr = htonl(groupAddress.toIPv4Address());
952
953 if (iface.isValid()) {
954 const QList<QNetworkAddressEntry> addressEntries = iface.addressEntries();
955 bool found = false;
956 for (const QNetworkAddressEntry &entry : addressEntries) {
957 const QHostAddress ip = entry.ip();
958 if (ip.protocol() == QAbstractSocket::IPv4Protocol) {
959 mreq4.imr_interface.s_addr = htonl(ip.toIPv4Address());
960 found = true;
961 break;
962 }
963 }
964 if (!found) {
965 d->setError(QAbstractSocket::NetworkError,
966 QNativeSocketEnginePrivate::NetworkUnreachableErrorString);
967 return false;
968 }
969 } else {
970 mreq4.imr_interface.s_addr = INADDR_ANY;
971 }
972 } else {
973 // unreachable
974 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
975 QNativeSocketEnginePrivate::ProtocolUnsupportedErrorString);
976 return false;
977 }
978
979 int res = setsockopt(d->socketDescriptor, level, sockOpt, sockArg, sockArgSize);
980 if (res == -1) {
981 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
982 QNativeSocketEnginePrivate::OperationUnsupportedErrorString);
983 return false;
984 }
985 return true;
986}
987
988bool QNativeSocketEnginePrivate::nativeJoinMulticastGroup(const QHostAddress &groupAddress,
989 const QNetworkInterface &iface)
990{
991 return multicastMembershipHelper(this,
992 IPV6_JOIN_GROUP,
993 IP_ADD_MEMBERSHIP,
994 groupAddress,
995 iface);
996}
997
998bool QNativeSocketEnginePrivate::nativeLeaveMulticastGroup(const QHostAddress &groupAddress,
999 const QNetworkInterface &iface)
1000{
1001 return multicastMembershipHelper(this,
1002 IPV6_LEAVE_GROUP,
1003 IP_DROP_MEMBERSHIP,
1004 groupAddress,
1005 iface);
1006}
1007
1008QNetworkInterface QNativeSocketEnginePrivate::nativeMulticastInterface() const
1009{
1010 if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
1011 uint v;
1012 QT_SOCKOPTLEN_T sizeofv = sizeof(v);
1013 if (::getsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *) &v, &sizeofv) == -1)
1014 return QNetworkInterface();
1015 return QNetworkInterface::interfaceFromIndex(v);
1016 }
1017
1018 struct in_addr v;
1019 v.s_addr = 0;
1020 QT_SOCKOPTLEN_T sizeofv = sizeof(v);
1021 if (::getsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, (char *) &v, &sizeofv) == -1)
1022 return QNetworkInterface();
1023 if (v.s_addr != 0 && sizeofv >= QT_SOCKOPTLEN_T(sizeof(v))) {
1024 QHostAddress ipv4(ntohl(v.s_addr));
1025 QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
1026 for (int i = 0; i < ifaces.count(); ++i) {
1027 const QNetworkInterface &iface = ifaces.at(i);
1028 if (!(iface.flags() & QNetworkInterface::CanMulticast))
1029 continue;
1030 QList<QNetworkAddressEntry> entries = iface.addressEntries();
1031 for (int j = 0; j < entries.count(); ++j) {
1032 const QNetworkAddressEntry &entry = entries.at(j);
1033 if (entry.ip() == ipv4)
1034 return iface;
1035 }
1036 }
1037 }
1038 return QNetworkInterface();
1039}
1040
1041bool QNativeSocketEnginePrivate::nativeSetMulticastInterface(const QNetworkInterface &iface)
1042{
1043
1044 if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
1045 uint v = iface.isValid() ? iface.index() : 0;
1046 return (::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *) &v, sizeof(v)) != -1);
1047 }
1048
1049 struct in_addr v;
1050 if (iface.isValid()) {
1051 QList<QNetworkAddressEntry> entries = iface.addressEntries();
1052 for (int i = 0; i < entries.count(); ++i) {
1053 const QNetworkAddressEntry &entry = entries.at(i);
1054 const QHostAddress &ip = entry.ip();
1055 if (ip.protocol() == QAbstractSocket::IPv4Protocol) {
1056 v.s_addr = htonl(ip.toIPv4Address());
1057 int r = ::setsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, (char *) &v, sizeof(v));
1058 if (r != -1)
1059 return true;
1060 }
1061 }
1062 return false;
1063 }
1064
1065 v.s_addr = INADDR_ANY;
1066 return (::setsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, (char *) &v, sizeof(v)) != -1);
1067}
1068
1069qint64 QNativeSocketEnginePrivate::nativeBytesAvailable() const
1070{
1071 unsigned long nbytes = 0;
1072 unsigned long dummy = 0;
1073 DWORD sizeWritten = 0;
1074 if (::WSAIoctl(socketDescriptor, FIONREAD, &dummy, sizeof(dummy), &nbytes, sizeof(nbytes), &sizeWritten, 0,0) == SOCKET_ERROR) {
1075 WS_ERROR_DEBUG(WSAGetLastError());
1076 return -1;
1077 }
1078
1079 // ioctlsocket sometimes reports 1 byte available for datagrams
1080 // while the following recvfrom returns -1 and claims connection
1081 // was reset (udp is connectionless). so we peek one byte to
1082 // catch this case and return 0 bytes available if recvfrom
1083 // fails.
1084 if (nbytes == 1 && socketType == QAbstractSocket::UdpSocket) {
1085 char c;
1086 WSABUF buf;
1087 buf.buf = &c;
1088 buf.len = sizeof(c);
1089 DWORD bytesReceived;
1090 DWORD flags = MSG_PEEK;
1091 if (::WSARecvFrom(socketDescriptor, &buf, 1, &bytesReceived, &flags, 0,0,0,0) == SOCKET_ERROR) {
1092 int err = WSAGetLastError();
1093 if (err != WSAECONNRESET && err != WSAENETRESET)
1094 return 0;
1095 } else {
1096 return bytesReceived;
1097 }
1098 }
1099 return nbytes;
1100}
1101
1102
1103bool QNativeSocketEnginePrivate::nativeHasPendingDatagrams() const
1104{
1105 // Create a sockaddr struct and reset its port number.
1106 qt_sockaddr storage;
1107 QT_SOCKLEN_T storageSize = sizeof(storage);
1108 memset(&storage, 0, storageSize);
1109
1110 bool result = false;
1111
1112 // Peek 0 bytes into the next message. The size of the message may
1113 // well be 0, so we check if there was a sender.
1114 char c;
1115 WSABUF buf;
1116 buf.buf = &c;
1117 buf.len = sizeof(c);
1118 DWORD available = 0;
1119 DWORD flags = MSG_PEEK;
1120 int ret = ::WSARecvFrom(socketDescriptor, &buf, 1, &available, &flags, &storage.a, &storageSize,0,0);
1121 int err = WSAGetLastError();
1122 if (ret == SOCKET_ERROR && err != WSAEMSGSIZE) {
1123 WS_ERROR_DEBUG(err);
1124 result = (err == WSAECONNRESET || err == WSAENETRESET);
1125 } else {
1126 // If there's no error, or if our buffer was too small, there must be
1127 // a pending datagram.
1128 result = true;
1129 }
1130
1131#if defined (QNATIVESOCKETENGINE_DEBUG)
1132 qDebug("QNativeSocketEnginePrivate::nativeHasPendingDatagrams() == %s",
1133 result ? "true" : "false");
1134#endif
1135 return result;
1136}
1137
1138
1139qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
1140{
1141 qint64 ret = -1;
1142 int recvResult = 0;
1143 DWORD flags;
1144 // We start at 1500 bytes (the MTU for Ethernet V2), which should catch
1145 // almost all uses (effective MTU for UDP under IPv4 is 1468), except
1146 // for localhost datagrams and those reassembled by the IP layer.
1147 char udpMessagePeekBuffer[1500];
1148 std::vector<WSABUF> buf;
1149 for (;;) {
1150 buf.resize(buf.size() + 5, {sizeof(udpMessagePeekBuffer), udpMessagePeekBuffer});
1151
1152 flags = MSG_PEEK;
1153 DWORD bytesRead = 0;
1154 recvResult = ::WSARecv(socketDescriptor, buf.data(), DWORD(buf.size()), &bytesRead, &flags, nullptr, nullptr);
1155 int err = WSAGetLastError();
1156 if (recvResult != SOCKET_ERROR) {
1157 ret = qint64(bytesRead);
1158 break;
1159 } else {
1160 switch (err) {
1161 case WSAEMSGSIZE:
1162 continue;
1163 case WSAECONNRESET:
1164 case WSAENETRESET:
1165 ret = 0;
1166 break;
1167 default:
1168 WS_ERROR_DEBUG(err);
1169 ret = -1;
1170 break;
1171 }
1172 break;
1173 }
1174 }
1175
1176#if defined (QNATIVESOCKETENGINE_DEBUG)
1177 qDebug("QNativeSocketEnginePrivate::nativePendingDatagramSize() == %lli", ret);
1178#endif
1179
1180 return ret;
1181}
1182
1183qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxLength, QIpPacketHeader *header,
1184 QAbstractSocketEngine::PacketHeaderOptions options)
1185{
1186 union {
1187 char cbuf[WSA_CMSG_SPACE(sizeof(struct in6_pktinfo)) + WSA_CMSG_SPACE(sizeof(int))];
1188 WSACMSGHDR align; // only to ensure alignment
1189 };
1190 WSAMSG msg;
1191 WSABUF buf;
1192 qt_sockaddr aa;
1193 char c;
1194 memset(&msg, 0, sizeof(msg));
1195 memset(&aa, 0, sizeof(aa));
1196
1197 // we need to receive at least one byte, even if our user isn't interested in it
1198 buf.buf = maxLength ? data : &c;
1199 buf.len = maxLength ? maxLength : 1;
1200 msg.lpBuffers = &buf;
1201 msg.dwBufferCount = 1;
1202 msg.name = reinterpret_cast<LPSOCKADDR>(&aa);
1203 msg.namelen = sizeof(aa);
1204 msg.Control.buf = cbuf;
1205 msg.Control.len = sizeof(cbuf);
1206
1207 DWORD flags = 0;
1208 DWORD bytesRead = 0;
1209 qint64 ret;
1210
1211 if (recvmsg)
1212 ret = recvmsg(socketDescriptor, &msg, &bytesRead, 0,0);
1213 else
1214 ret = ::WSARecvFrom(socketDescriptor, &buf, 1, &bytesRead, &flags, msg.name, &msg.namelen,0,0);
1215 if (ret == SOCKET_ERROR) {
1216 int err = WSAGetLastError();
1217 if (err == WSAEMSGSIZE) {
1218 // it is ok the buffer was to small if bytesRead is larger than
1219 // maxLength then assume bytes read is really maxLenth
1220 ret = qint64(bytesRead) > maxLength ? maxLength : qint64(bytesRead);
1221 if (options & QNativeSocketEngine::WantDatagramSender)
1222 qt_socket_getPortAndAddress(socketDescriptor, &aa, &header->senderPort, &header->senderAddress);
1223 } else {
1224 WS_ERROR_DEBUG(err);
1225 switch (err) {
1226 case WSAENETRESET:
1227 setError(QAbstractSocket::NetworkError, NetworkDroppedConnectionErrorString);
1228 break;
1229 case WSAECONNRESET:
1230 setError(QAbstractSocket::ConnectionRefusedError, ConnectionResetErrorString);
1231 break;
1232 default:
1233 setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
1234 break;
1235 }
1236 ret = -1;
1237 if (header)
1238 header->clear();
1239 }
1240 } else {
1241 ret = qint64(bytesRead);
1242 if (options & QNativeSocketEngine::WantDatagramSender)
1243 qt_socket_getPortAndAddress(socketDescriptor, &aa, &header->senderPort, &header->senderAddress);
1244 }
1245
1246 if (ret != -1 && recvmsg && options != QAbstractSocketEngine::WantNone) {
1247 // get the ancillary data
1248 header->destinationPort = localPort;
1249 WSACMSGHDR *cmsgptr;
1250 for (cmsgptr = WSA_CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
1251 cmsgptr = WSA_CMSG_NXTHDR(&msg, cmsgptr)) {
1252 if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_PKTINFO
1253 && cmsgptr->cmsg_len >= WSA_CMSG_LEN(sizeof(in6_pktinfo))) {
1254 in6_pktinfo *info = reinterpret_cast<in6_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
1255
1256 header->destinationAddress.setAddress(reinterpret_cast<quint8 *>(&info->ipi6_addr));
1257 header->ifindex = info->ipi6_ifindex;
1258 if (header->ifindex)
1259 header->destinationAddress.setScopeId(QString::number(info->ipi6_ifindex));
1260 }
1261 if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_PKTINFO
1262 && cmsgptr->cmsg_len >= WSA_CMSG_LEN(sizeof(in_pktinfo))) {
1263 in_pktinfo *info = reinterpret_cast<in_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
1264 u_long addr;
1265 WSANtohl(socketDescriptor, info->ipi_addr.s_addr, &addr);
1266 header->destinationAddress.setAddress(addr);
1267 header->ifindex = info->ipi_ifindex;
1268 }
1269
1270 if (cmsgptr->cmsg_len == WSA_CMSG_LEN(sizeof(int))
1271 && ((cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_HOPLIMIT)
1272 || (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_TTL))) {
1273 header->hopLimit = *reinterpret_cast<int *>(WSA_CMSG_DATA(cmsgptr));
1274 }
1275 }
1276 }
1277
1278#if defined (QNATIVESOCKETENGINE_DEBUG)
1279 bool printSender = (ret != -1 && (options & QNativeSocketEngine::WantDatagramSender) != 0);
1280 qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
1281 data, qt_prettyDebug(data, qMin<qint64>(ret, 16), ret).data(), maxLength,
1282 printSender ? header->senderAddress.toString().toLatin1().constData() : "(unknown)",
1283 printSender ? header->senderPort : 0, ret);
1284#endif
1285
1286 return ret;
1287}
1288
1289
1290qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
1291 const QIpPacketHeader &header)
1292{
1293 union {
1294 char cbuf[WSA_CMSG_SPACE(sizeof(struct in6_pktinfo)) + WSA_CMSG_SPACE(sizeof(int))];
1295 WSACMSGHDR align; // ensures alignment
1296 };
1297 WSACMSGHDR *cmsgptr = &align;
1298 WSAMSG msg;
1299 WSABUF buf;
1300 qt_sockaddr aa;
1301
1302 memset(&msg, 0, sizeof(msg));
1303 memset(&aa, 0, sizeof(aa));
1304 buf.buf = len ? (char*)data : 0;
1305 msg.lpBuffers = &buf;
1306 msg.dwBufferCount = 1;
1307 msg.name = &aa.a;
1308 buf.len = len;
1309
1310 setPortAndAddress(header.destinationPort, header.destinationAddress, &aa, &msg.namelen);
1311
1312 uint oldIfIndex = 0;
1313 bool mustSetIpv6MulticastIf = false;
1314
1315 if (msg.namelen == sizeof(aa.a6)) {
1316 // sending IPv6
1317 if (header.hopLimit != -1) {
1318 msg.Control.len += WSA_CMSG_SPACE(sizeof(int));
1319 cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(int));
1320 cmsgptr->cmsg_level = IPPROTO_IPV6;
1321 cmsgptr->cmsg_type = IPV6_HOPLIMIT;
1322 memcpy(WSA_CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
1323 cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
1324 + WSA_CMSG_SPACE(sizeof(int)));
1325 }
1326 if (!header.senderAddress.isNull()) {
1327 struct in6_pktinfo *data = reinterpret_cast<in6_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
1328 memset(data, 0, sizeof(*data));
1329 msg.Control.len += WSA_CMSG_SPACE(sizeof(*data));
1330 cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(*data));
1331 cmsgptr->cmsg_level = IPPROTO_IPV6;
1332 cmsgptr->cmsg_type = IPV6_PKTINFO;
1333 data->ipi6_ifindex = header.ifindex;
1334
1335 Q_IPV6ADDR tmp = header.senderAddress.toIPv6Address();
1336 memcpy(&data->ipi6_addr, &tmp, sizeof(tmp));
1337 cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
1338 + WSA_CMSG_SPACE(sizeof(*data)));
1339 } else if (header.ifindex != 0) {
1340 // Unlike other operating systems, setting the interface index in the in6_pktinfo
1341 // structure above and leaving the ipi6_addr set to :: will cause the packets to be
1342 // sent with source address ::. So we have to use IPV6_MULTICAST_IF, which MSDN is
1343 // quite clear that "This option does not change the default interface for receiving
1344 // IPv6 multicast traffic."
1345 QT_SOCKOPTLEN_T len = sizeof(oldIfIndex);
1346 if (::getsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1347 reinterpret_cast<char *>(&oldIfIndex), &len) == -1
1348 || ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1349 reinterpret_cast<const char *>(&header.ifindex), sizeof(header.ifindex)) == -1) {
1350 setError(QAbstractSocket::NetworkError, SendDatagramErrorString);
1351 return -1;
1352 }
1353 mustSetIpv6MulticastIf = true;
1354 }
1355 } else {
1356 // sending IPv4
1357 if (header.hopLimit != -1) {
1358 msg.Control.len += WSA_CMSG_SPACE(sizeof(int));
1359 cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(int));
1360 cmsgptr->cmsg_level = IPPROTO_IP;
1361 cmsgptr->cmsg_type = IP_TTL;
1362 memcpy(WSA_CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
1363 cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
1364 + WSA_CMSG_SPACE(sizeof(int)));
1365 }
1366 if (header.ifindex != 0 || !header.senderAddress.isNull()) {
1367 struct in_pktinfo *data = reinterpret_cast<in_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
1368 memset(data, 0, sizeof(*data));
1369 msg.Control.len += WSA_CMSG_SPACE(sizeof(*data));
1370 cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(*data));
1371 cmsgptr->cmsg_level = IPPROTO_IP;
1372 cmsgptr->cmsg_type = IP_PKTINFO;
1373 data->ipi_ifindex = header.ifindex;
1374 WSAHtonl(socketDescriptor, header.senderAddress.toIPv4Address(), &data->ipi_addr.s_addr);
1375 cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
1376 + WSA_CMSG_SPACE(sizeof(*data)));
1377 }
1378 }
1379
1380 if (msg.Control.len != 0)
1381 msg.Control.buf = cbuf;
1382
1383 DWORD flags = 0;
1384 DWORD bytesSent = 0;
1385 qint64 ret = -1;
1386 if (sendmsg) {
1387 ret = sendmsg(socketDescriptor, &msg, flags, &bytesSent, 0,0);
1388 } else {
1389 ret = ::WSASendTo(socketDescriptor, &buf, 1, &bytesSent, flags, msg.name, msg.namelen, 0,0);
1390 }
1391 if (ret == SOCKET_ERROR) {
1392 int err = WSAGetLastError();
1393 WS_ERROR_DEBUG(err);
1394 switch (err) {
1395 case WSAEMSGSIZE:
1396 setError(QAbstractSocket::DatagramTooLargeError, DatagramTooLargeErrorString);
1397 break;
1398 default:
1399 setError(QAbstractSocket::NetworkError, SendDatagramErrorString);
1400 break;
1401 }
1402 ret = -1;
1403 } else {
1404 ret = qint64(bytesSent);
1405 }
1406
1407 if (mustSetIpv6MulticastIf) {
1408 // undo what we did above
1409 ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1410 reinterpret_cast<char *>(&oldIfIndex), sizeof(oldIfIndex));
1411 }
1412
1413#if defined (QNATIVESOCKETENGINE_DEBUG)
1414 qDebug("QNativeSocketEnginePrivate::nativeSendDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli", data,
1415 qt_prettyDebug(data, qMin<qint64>(len, 16), len).data(), len,
1416 header.destinationAddress.toString().toLatin1().constData(),
1417 header.destinationPort, ret);
1418#endif
1419
1420 return ret;
1421}
1422
1423
1424qint64 QNativeSocketEnginePrivate::nativeWrite(const char *data, qint64 len)
1425{
1426 Q_Q(QNativeSocketEngine);
1427 qint64 ret = 0;
1428 qint64 bytesToSend = len;
1429
1430 for (;;) {
1431 WSABUF buf;
1432 buf.buf = const_cast<char*>(data) + ret;
1433 buf.len = bytesToSend;
1434 DWORD flags = 0;
1435 DWORD bytesWritten = 0;
1436
1437 int socketRet = ::WSASend(socketDescriptor, &buf, 1, &bytesWritten, flags, 0,0);
1438
1439 ret += qint64(bytesWritten);
1440
1441 int err;
1442 if (socketRet != SOCKET_ERROR) {
1443 if (ret == len)
1444 break;
1445 else
1446 continue;
1447 } else if ((err = WSAGetLastError()) == WSAEWOULDBLOCK) {
1448 break;
1449 } else if (err == WSAENOBUFS) {
1450 // this function used to not send more than 49152 per call to WSASendTo
1451 // to avoid getting a WSAENOBUFS. However this is a performance regression
1452 // and we think it only appears with old windows versions. We now handle the
1453 // WSAENOBUFS and hope it never appears anyway.
1454 // just go on, the next loop run we will try a smaller number
1455 } else {
1456 WS_ERROR_DEBUG(err);
1457 switch (err) {
1458 case WSAECONNRESET:
1459 case WSAECONNABORTED:
1460 ret = -1;
1461 setError(QAbstractSocket::NetworkError, WriteErrorString);
1462 q->close();
1463 break;
1464 default:
1465 break;
1466 }
1467 break;
1468 }
1469
1470 // for next send:
1471 bytesToSend = qMin<qint64>(49152, len - ret);
1472 }
1473
1474#if defined (QNATIVESOCKETENGINE_DEBUG)
1475 qDebug("QNativeSocketEnginePrivate::nativeWrite(%p \"%s\", %lli) == %lli",
1476 data, qt_prettyDebug(data, qMin(int(ret), 16), int(ret)).data(), len, ret);
1477#endif
1478
1479 return ret;
1480}
1481
1482qint64 QNativeSocketEnginePrivate::nativeRead(char *data, qint64 maxLength)
1483{
1484 qint64 ret = -1;
1485 WSABUF buf;
1486 buf.buf = data;
1487 buf.len = maxLength;
1488 DWORD flags = 0;
1489 DWORD bytesRead = 0;
1490 if (::WSARecv(socketDescriptor, &buf, 1, &bytesRead, &flags, 0,0) == SOCKET_ERROR) {
1491 int err = WSAGetLastError();
1492 WS_ERROR_DEBUG(err);
1493 switch (err) {
1494 case WSAEWOULDBLOCK:
1495 ret = -2;
1496 break;
1497 case WSAEBADF:
1498 case WSAEINVAL:
1499 //error string is now set in read(), not here in nativeRead()
1500 break;
1501 case WSAECONNRESET:
1502 case WSAECONNABORTED:
1503 // for tcp sockets this will be handled in QNativeSocketEngine::read
1504 ret = 0;
1505 break;
1506 default:
1507 break;
1508 }
1509 } else {
1510 if (WSAGetLastError() == WSAEWOULDBLOCK)
1511 ret = -2;
1512 else
1513 ret = qint64(bytesRead);
1514 }
1515
1516#if defined (QNATIVESOCKETENGINE_DEBUG)
1517 if (ret != -2) {
1518 qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %lli) == %lli",
1519 data, qt_prettyDebug(data, qMin(int(bytesRead), 16), int(bytesRead)).data(), maxLength, ret);
1520 } else {
1521 qDebug("QNativeSocketEnginePrivate::nativeRead(%p, %lli) == -2 (WOULD BLOCK)",
1522 data, maxLength);
1523 }
1524#endif
1525
1526 return ret;
1527}
1528
1529int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) const
1530{
1531 bool readEnabled = selectForRead && readNotifier && readNotifier->isEnabled();
1532 if (readEnabled)
1533 readNotifier->setEnabled(false);
1534
1535 fd_set fds;
1536
1537 int ret = 0;
1538
1539 memset(&fds, 0, sizeof(fd_set));
1540 fds.fd_count = 1;
1541 fds.fd_array[0] = (SOCKET)socketDescriptor;
1542
1543 struct timeval tv;
1544 tv.tv_sec = timeout / 1000;
1545 tv.tv_usec = (timeout % 1000) * 1000;
1546
1547 if (selectForRead) {
1548 ret = select(0, &fds, 0, 0, timeout < 0 ? 0 : &tv);
1549 } else {
1550 // select for write
1551
1552 // Windows needs this to report errors when connecting a socket ...
1553 fd_set fdexception;
1554 FD_ZERO(&fdexception);
1555 FD_SET((SOCKET)socketDescriptor, &fdexception);
1556
1557 ret = select(0, 0, &fds, &fdexception, timeout < 0 ? 0 : &tv);
1558
1559 // ... but if it is actually set, pretend it did not happen
1560 if (ret > 0 && FD_ISSET((SOCKET)socketDescriptor, &fdexception))
1561 ret--;
1562 }
1563
1564 if (readEnabled)
1565 readNotifier->setEnabled(true);
1566
1567 return ret;
1568}
1569
1570int QNativeSocketEnginePrivate::nativeSelect(int timeout,
1571 bool checkRead, bool checkWrite,
1572 bool *selectForRead, bool *selectForWrite) const
1573{
1574 bool readEnabled = checkRead && readNotifier && readNotifier->isEnabled();
1575 if (readEnabled)
1576 readNotifier->setEnabled(false);
1577
1578 fd_set fdread;
1579 fd_set fdwrite;
1580 fd_set fdexception;
1581
1582 int ret = 0;
1583
1584 memset(&fdread, 0, sizeof(fd_set));
1585 if (checkRead) {
1586 fdread.fd_count = 1;
1587 fdread.fd_array[0] = (SOCKET)socketDescriptor;
1588 }
1589 memset(&fdwrite, 0, sizeof(fd_set));
1590 FD_ZERO(&fdexception);
1591 if (checkWrite) {
1592 fdwrite.fd_count = 1;
1593 fdwrite.fd_array[0] = (SOCKET)socketDescriptor;
1594
1595 // Windows needs this to report errors when connecting a socket
1596 FD_SET((SOCKET)socketDescriptor, &fdexception);
1597 }
1598
1599 struct timeval tv;
1600 tv.tv_sec = timeout / 1000;
1601 tv.tv_usec = (timeout % 1000) * 1000;
1602
1603 ret = select(socketDescriptor + 1, &fdread, &fdwrite, &fdexception, timeout < 0 ? 0 : &tv);
1604
1605 //... but if it is actually set, pretend it did not happen
1606 if (ret > 0 && FD_ISSET((SOCKET)socketDescriptor, &fdexception))
1607 ret--;
1608
1609 if (readEnabled)
1610 readNotifier->setEnabled(true);
1611
1612 if (ret <= 0)
1613 return ret;
1614
1615 *selectForRead = FD_ISSET((SOCKET)socketDescriptor, &fdread);
1616 *selectForWrite = FD_ISSET((SOCKET)socketDescriptor, &fdwrite);
1617
1618 return ret;
1619}
1620
1621void QNativeSocketEnginePrivate::nativeClose()
1622{
1623#if defined (QTCPSOCKETENGINE_DEBUG)
1624 qDebug("QNativeSocketEnginePrivate::nativeClose()");
1625#endif
1626 // We were doing a setsockopt here before with SO_DONTLINGER. (However with kind of wrong
1627 // usage of parameters, it wants a BOOL but we used a struct and pretended it to be bool).
1628 // We don't think setting this option should be done here, if a user wants it she/he can
1629 // do it manually with socketDescriptor()/setSocketDescriptor();
1630 ::closesocket(socketDescriptor);
1631}
1632
1633QT_END_NAMESPACE
1634

Warning: That file was not part of the compilation database. It may have many parsing errors.