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