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

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

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

File size: 32.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42//#define QNATIVESOCKETENGINE_DEBUG
43#include "qnativesocketengine_p.h"
44#include "private/qnet_unix_p.h"
45#include "qiodevice.h"
46#include "qhostaddress.h"
47#include "qelapsedtimer.h"
48#include "qvarlengtharray.h"
49#include <time.h>
50#include <errno.h>
51#include <fcntl.h>
52#ifndef QT_NO_IPV6IFNAME
53#include <net/if.h>
54#endif
55#ifndef QT_NO_IPV6IFNAME
56#include <net/if.h>
57#endif
58#ifdef QT_LINUXBASE
59#include <arpa/inet.h>
60#endif
61
62#if defined QNATIVESOCKETENGINE_DEBUG
63#include <qstring.h>
64#include <ctype.h>
65#endif
66
67#ifdef Q_OS_SYMBIAN // ### TODO: Are these headers right?
68#include <sys/socket.h>
69#include <netinet/in.h>
70#else
71#include <netinet/tcp.h>
72#endif
73
74QT_BEGIN_NAMESPACE
75
76#if defined QNATIVESOCKETENGINE_DEBUG
77
78/*
79 Returns a human readable representation of the first \a len
80 characters in \a data.
81*/
82static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
83{
84 if (!data) return "(null)";
85 QByteArray out;
86 for (int i = 0; i < len; ++i) {
87 char c = data[i];
88 if (isprint(c)) {
89 out += c;
90 } else switch (c) {
91 case '\n': out += "\\n"; break;
92 case '\r': out += "\\r"; break;
93 case '\t': out += "\\t"; break;
94 default:
95 QString tmp;
96 tmp.sprintf("\\%o", c);
97 out += tmp.toLatin1();
98 }
99 }
100
101 if (len < maxSize)
102 out += "...";
103
104 return out;
105}
106#endif
107
108static void qt_ignore_sigpipe()
109{
110#ifndef Q_NO_POSIX_SIGNALS
111 // Set to ignore SIGPIPE once only.
112 static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0);
113 if (atom.testAndSetRelaxed(0, 1)) {
114 struct sigaction noaction;
115 memset(&noaction, 0, sizeof(noaction));
116 noaction.sa_handler = SIG_IGN;
117 ::sigaction(SIGPIPE, &noaction, 0);
118 }
119#else
120 // Posix signals are not supported by the underlying platform
121 // so we don't need to ignore sigpipe signal explicitly
122#endif
123}
124
125/*
126 Extracts the port and address from a sockaddr, and stores them in
127 \a port and \a addr if they are non-null.
128*/
129static inline void qt_socket_getPortAndAddress(const qt_sockaddr *s, quint16 *port, QHostAddress *addr)
130{
131#if !defined(QT_NO_IPV6)
132 if (s->a.sa_family == AF_INET6) {
133 Q_IPV6ADDR tmp;
134 memcpy(&tmp, &s->a6.sin6_addr, sizeof(tmp));
135 if (addr) {
136 QHostAddress tmpAddress;
137 tmpAddress.setAddress(tmp);
138 *addr = tmpAddress;
139#ifndef QT_NO_IPV6IFNAME
140 char scopeid[IFNAMSIZ];
141 if (::if_indextoname(s->a6.sin6_scope_id, scopeid)) {
142 addr->setScopeId(QLatin1String(scopeid));
143 } else
144#endif
145 addr->setScopeId(QString::number(s->a6.sin6_scope_id));
146 }
147 if (port)
148 *port = ntohs(s->a6.sin6_port);
149 return;
150 }
151#endif
152 if (port)
153 *port = ntohs(s->a4.sin_port);
154 if (addr) {
155 QHostAddress tmpAddress;
156 tmpAddress.setAddress(ntohl(s->a4.sin_addr.s_addr));
157 *addr = tmpAddress;
158 }
159}
160
161/*! \internal
162
163 Creates and returns a new socket descriptor of type \a socketType
164 and \a socketProtocol. Returns -1 on failure.
165*/
166bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType,
167 QAbstractSocket::NetworkLayerProtocol socketProtocol)
168{
169#ifndef QT_NO_IPV6
170 int protocol = (socketProtocol == QAbstractSocket::IPv6Protocol) ? AF_INET6 : AF_INET;
171#else
172 Q_UNUSED(socketProtocol);
173 int protocol = AF_INET;
174#endif
175 int type = (socketType == QAbstractSocket::UdpSocket) ? SOCK_DGRAM : SOCK_STREAM;
176#ifdef Q_OS_SYMBIAN
177 int socket = ::socket(protocol, type, 0);
178#else
179 int socket = qt_safe_socket(protocol, type, 0);
180#endif
181
182 if (socket <= 0) {
183 switch (errno) {
184 case EPROTONOSUPPORT:
185 case EAFNOSUPPORT:
186 case EINVAL:
187 setError(QAbstractSocket::UnsupportedSocketOperationError, ProtocolUnsupportedErrorString);
188 break;
189 case ENFILE:
190 case EMFILE:
191 case ENOBUFS:
192 case ENOMEM:
193 setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
194 break;
195 case EACCES:
196 setError(QAbstractSocket::SocketAccessError, AccessErrorString);
197 break;
198 default:
199 break;
200 }
201
202 return false;
203 }
204
205 socketDescriptor = socket;
206 return true;
207}
208
209/*
210 Returns the value of the socket option \a opt.
211*/
212int QNativeSocketEnginePrivate::option(QNativeSocketEngine::SocketOption opt) const
213{
214 Q_Q(const QNativeSocketEngine);
215 if (!q->isValid())
216 return -1;
217
218 int n = -1;
219 int level = SOL_SOCKET; // default
220
221 switch (opt) {
222 case QNativeSocketEngine::ReceiveBufferSocketOption:
223 n = SO_RCVBUF;
224 break;
225 case QNativeSocketEngine::SendBufferSocketOption:
226 n = SO_SNDBUF;
227 break;
228 case QNativeSocketEngine::NonBlockingSocketOption:
229 break;
230 case QNativeSocketEngine::BroadcastSocketOption:
231 break;
232 case QNativeSocketEngine::AddressReusable:
233 n = SO_REUSEADDR;
234 break;
235 case QNativeSocketEngine::BindExclusively:
236 return true;
237 case QNativeSocketEngine::ReceiveOutOfBandData:
238 n = SO_OOBINLINE;
239 break;
240 case QNativeSocketEngine::LowDelayOption:
241 level = IPPROTO_TCP;
242 n = TCP_NODELAY;
243 break;
244 case QNativeSocketEngine::KeepAliveOption:
245 n = SO_KEEPALIVE;
246 break;
247 }
248
249 int v = -1;
250 QT_SOCKOPTLEN_T len = sizeof(v);
251 if (::getsockopt(socketDescriptor, level, n, (char *) &v, &len) != -1)
252 return v;
253
254 return -1;
255}
256
257
258/*
259 Sets the socket option \a opt to \a v.
260*/
261bool QNativeSocketEnginePrivate::setOption(QNativeSocketEngine::SocketOption opt, int v)
262{
263 Q_Q(QNativeSocketEngine);
264 if (!q->isValid())
265 return false;
266
267 int n = 0;
268 int level = SOL_SOCKET; // default
269
270 switch (opt) {
271 case QNativeSocketEngine::ReceiveBufferSocketOption:
272 n = SO_RCVBUF;
273 break;
274 case QNativeSocketEngine::SendBufferSocketOption:
275 n = SO_SNDBUF;
276 break;
277 case QNativeSocketEngine::BroadcastSocketOption:
278 n = SO_BROADCAST;
279 break;
280 case QNativeSocketEngine::NonBlockingSocketOption: {
281 // Make the socket nonblocking.
282#if !defined(Q_OS_VXWORKS)
283 int flags = ::fcntl(socketDescriptor, F_GETFL, 0);
284 if (flags == -1) {
285#ifdef QNATIVESOCKETENGINE_DEBUG
286 perror("QNativeSocketEnginePrivate::setOption(): fcntl(F_GETFL) failed");
287#endif
288 return false;
289 }
290 if (::fcntl(socketDescriptor, F_SETFL, flags | O_NONBLOCK) == -1) {
291#ifdef QNATIVESOCKETENGINE_DEBUG
292 perror("QNativeSocketEnginePrivate::setOption(): fcntl(F_SETFL) failed");
293#endif
294 return false;
295 }
296#else // Q_OS_VXWORKS
297 int onoff = 1;
298#ifdef Q_OS_SYMBIAN
299 if (::ioctl(socketDescriptor, FIONBIO, &onoff) < 0) {
300#else
301 if (qt_safe_ioctl(socketDescriptor, FIONBIO, &onoff) < 0) {
302#endif
303#ifdef QNATIVESOCKETENGINE_DEBUG
304 perror("QNativeSocketEnginePrivate::setOption(): ioctl(FIONBIO, 1) failed");
305#endif
306 return false;
307 }
308#endif // Q_OS_VXWORKS
309 return true;
310 }
311 case QNativeSocketEngine::AddressReusable:
312#if defined(SO_REUSEPORT) && !defined(Q_OS_SYMBIAN)
313 n = SO_REUSEPORT;
314#else
315 n = SO_REUSEADDR;
316#endif
317 break;
318 case QNativeSocketEngine::BindExclusively:
319 return true;
320 case QNativeSocketEngine::ReceiveOutOfBandData:
321 n = SO_OOBINLINE;
322 break;
323 case QNativeSocketEngine::LowDelayOption:
324 level = IPPROTO_TCP;
325 n = TCP_NODELAY;
326 break;
327 case QNativeSocketEngine::KeepAliveOption:
328 n = SO_KEEPALIVE;
329 break;
330 }
331
332 return ::setsockopt(socketDescriptor, level, n, (char *) &v, sizeof(v)) == 0;
333}
334
335bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16 port)
336{
337#ifdef QNATIVESOCKETENGINE_DEBUG
338 qDebug("QNativeSocketEnginePrivate::nativeConnect() : %d ", socketDescriptor);
339#endif
340
341 struct sockaddr_in sockAddrIPv4;
342 struct sockaddr *sockAddrPtr = 0;
343 QT_SOCKLEN_T sockAddrSize = 0;
344
345#if !defined(QT_NO_IPV6)
346 struct sockaddr_in6 sockAddrIPv6;
347
348 if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
349 memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
350 sockAddrIPv6.sin6_family = AF_INET6;
351 sockAddrIPv6.sin6_port = htons(port);
352
353 QString scopeid = addr.scopeId();
354 bool ok;
355 sockAddrIPv6.sin6_scope_id = scopeid.toInt(&ok);
356#ifndef QT_NO_IPV6IFNAME
357 if (!ok)
358 sockAddrIPv6.sin6_scope_id = ::if_nametoindex(scopeid.toLatin1());
359#endif
360 Q_IPV6ADDR ip6 = addr.toIPv6Address();
361 memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &ip6, sizeof(ip6));
362
363 sockAddrSize = sizeof(sockAddrIPv6);
364 sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
365 } else
366#if 0
367 {}
368#endif
369#endif
370 if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
371 memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
372 sockAddrIPv4.sin_family = AF_INET;
373 sockAddrIPv4.sin_port = htons(port);
374 sockAddrIPv4.sin_addr.s_addr = htonl(addr.toIPv4Address());
375
376 sockAddrSize = sizeof(sockAddrIPv4);
377 sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
378 } else {
379 // unreachable
380 }
381#ifdef Q_OS_SYMBIAN
382 int connectResult = ::connect(socketDescriptor, sockAddrPtr, sockAddrSize);
383#else
384 int connectResult = qt_safe_connect(socketDescriptor, sockAddrPtr, sockAddrSize);
385#endif
386 if (connectResult == -1) {
387 switch (errno) {
388 case EISCONN:
389 socketState = QAbstractSocket::ConnectedState;
390 break;
391 case ECONNREFUSED:
392 case EINVAL:
393 setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
394 socketState = QAbstractSocket::UnconnectedState;
395 break;
396 case ETIMEDOUT:
397 setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
398 break;
399 case EHOSTUNREACH:
400 setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
401 socketState = QAbstractSocket::UnconnectedState;
402 break;
403 case ENETUNREACH:
404 setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
405 socketState = QAbstractSocket::UnconnectedState;
406 break;
407 case EADDRINUSE:
408 setError(QAbstractSocket::NetworkError, AddressInuseErrorString);
409 break;
410 case EINPROGRESS:
411 case EALREADY:
412 setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
413 socketState = QAbstractSocket::ConnectingState;
414 break;
415 case EAGAIN:
416 setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
417 setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
418 break;
419 case EACCES:
420 case EPERM:
421 setError(QAbstractSocket::SocketAccessError, AccessErrorString);
422 socketState = QAbstractSocket::UnconnectedState;
423 break;
424 case EAFNOSUPPORT:
425 case EBADF:
426 case EFAULT:
427 case ENOTSOCK:
428#ifdef Q_OS_SYMBIAN
429 case EPIPE:
430#endif
431 socketState = QAbstractSocket::UnconnectedState;
432 default:
433 break;
434 }
435
436 if (socketState != QAbstractSocket::ConnectedState) {
437#if defined (QNATIVESOCKETENGINE_DEBUG)
438 qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
439 addr.toString().toLatin1().constData(), port,
440 socketState == QAbstractSocket::ConnectingState
441 ? "Connection in progress" : socketErrorString.toLatin1().constData());
442#endif
443 return false;
444 }
445 }
446
447#if defined (QNATIVESOCKETENGINE_DEBUG)
448 qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == true",
449 addr.toString().toLatin1().constData(), port);
450#endif
451
452 socketState = QAbstractSocket::ConnectedState;
453 return true;
454}
455
456bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16 port)
457{
458 struct sockaddr_in sockAddrIPv4;
459 struct sockaddr *sockAddrPtr = 0;
460 QT_SOCKLEN_T sockAddrSize = 0;
461
462#if !defined(QT_NO_IPV6)
463 struct sockaddr_in6 sockAddrIPv6;
464
465 if (address.protocol() == QAbstractSocket::IPv6Protocol) {
466 memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
467 sockAddrIPv6.sin6_family = AF_INET6;
468 sockAddrIPv6.sin6_port = htons(port);
469#ifndef QT_NO_IPV6IFNAME
470 sockAddrIPv6.sin6_scope_id = ::if_nametoindex(address.scopeId().toLatin1().data());
471#else
472 sockAddrIPv6.sin6_scope_id = address.scopeId().toInt();
473#endif
474 Q_IPV6ADDR tmp = address.toIPv6Address();
475 memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
476 sockAddrSize = sizeof(sockAddrIPv6);
477 sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
478 } else
479#endif
480 if (address.protocol() == QAbstractSocket::IPv4Protocol) {
481 memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
482 sockAddrIPv4.sin_family = AF_INET;
483 sockAddrIPv4.sin_port = htons(port);
484 sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
485 sockAddrSize = sizeof(sockAddrIPv4);
486 sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
487 } else {
488 // unreachable
489 }
490
491 int bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);
492
493 if (bindResult < 0) {
494 switch(errno) {
495 case EADDRINUSE:
496 setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
497 break;
498 case EACCES:
499 setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);
500 break;
501 case EINVAL:
502 setError(QAbstractSocket::UnsupportedSocketOperationError, OperationUnsupportedErrorString);
503 break;
504 case EADDRNOTAVAIL:
505 setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);
506 break;
507 default:
508 break;
509 }
510
511#if defined (QNATIVESOCKETENGINE_DEBUG)
512 qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
513 address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
514#endif
515
516 return false;
517 }
518
519#if defined (QNATIVESOCKETENGINE_DEBUG)
520 qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == true",
521 address.toString().toLatin1().constData(), port);
522#endif
523 socketState = QAbstractSocket::BoundState;
524 return true;
525}
526
527bool QNativeSocketEnginePrivate::nativeListen(int backlog)
528{
529#ifdef Q_OS_SYMBIAN
530 if (::listen(socketDescriptor, backlog) < 0) {
531#else
532 if (qt_safe_listen(socketDescriptor, backlog) < 0) {
533#endif
534 switch (errno) {
535 case EADDRINUSE:
536 setError(QAbstractSocket::AddressInUseError,
537 PortInuseErrorString);
538 break;
539 default:
540 break;
541 }
542
543#if defined (QNATIVESOCKETENGINE_DEBUG)
544 qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == false (%s)",
545 backlog, socketErrorString.toLatin1().constData());
546#endif
547 return false;
548 }
549
550#if defined (QNATIVESOCKETENGINE_DEBUG)
551 qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == true", backlog);
552#endif
553
554 socketState = QAbstractSocket::ListeningState;
555 return true;
556}
557
558int QNativeSocketEnginePrivate::nativeAccept()
559{
560#ifdef Q_OS_SYMBIAN
561 int acceptedDescriptor = ::accept(socketDescriptor, 0, 0);
562#else
563 int acceptedDescriptor = qt_safe_accept(socketDescriptor, 0, 0);
564#endif
565
566 return acceptedDescriptor;
567}
568
569qint64 QNativeSocketEnginePrivate::nativeBytesAvailable() const
570{
571 int nbytes = 0;
572 // gives shorter than true amounts on Unix domain sockets.
573 qint64 available = 0;
574#ifdef Q_OS_SYMBIAN
575 if (::ioctl(socketDescriptor, FIONREAD, (char *) &nbytes) >= 0)
576#else
577 if (qt_safe_ioctl(socketDescriptor, FIONREAD, (char *) &nbytes) >= 0)
578#endif
579 available = (qint64) nbytes;
580
581#if defined (QNATIVESOCKETENGINE_DEBUG)
582 qDebug("QNativeSocketEnginePrivate::nativeBytesAvailable() == %lli", available);
583#endif
584 return available;
585}
586
587bool QNativeSocketEnginePrivate::nativeHasPendingDatagrams() const
588{
589 // Create a sockaddr struct and reset its port number.
590 qt_sockaddr storage;
591 QT_SOCKLEN_T storageSize = sizeof(storage);
592 memset(&storage, 0, storageSize);
593
594 // Peek 0 bytes into the next message. The size of the message may
595 // well be 0, so we can't check recvfrom's return value.
596 ssize_t readBytes;
597#ifdef Q_OS_SYMBIAN
598 char c;
599 readBytes = ::recvfrom(socketDescriptor, &c, 1, MSG_PEEK, &storage.a, &storageSize);
600#else
601 do {
602 char c;
603 readBytes = ::recvfrom(socketDescriptor, &c, 1, MSG_PEEK, &storage.a, &storageSize);
604 } while (readBytes == -1 && errno == EINTR);
605#endif
606
607 // If there's no error, or if our buffer was too small, there must be a
608 // pending datagram.
609 bool result = (readBytes != -1) || errno == EMSGSIZE;
610
611#if defined (QNATIVESOCKETENGINE_DEBUG)
612 qDebug("QNativeSocketEnginePrivate::nativeHasPendingDatagrams() == %s",
613 result ? "true" : "false");
614#endif
615 return result;
616}
617
618#ifdef Q_OS_SYMBIAN
619qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
620{
621 size_t nbytes = 0;
622 ::ioctl(socketDescriptor, E32IONREAD, (char *) &nbytes);
623 return qint64(nbytes-28);
624}
625#else
626qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
627{
628 QVarLengthArray<char, 8192> udpMessagePeekBuffer(8192);
629 ssize_t recvResult = -1;
630
631 for (;;) {
632 // the data written to udpMessagePeekBuffer is discarded, so
633 // this function is still reentrant although it might not look
634 // so.
635 recvResult = ::recv(socketDescriptor, udpMessagePeekBuffer.data(),
636 udpMessagePeekBuffer.size(), MSG_PEEK);
637 if (recvResult == -1 && errno == EINTR)
638 continue;
639
640 if (recvResult != (ssize_t) udpMessagePeekBuffer.size())
641 break;
642
643 udpMessagePeekBuffer.resize(udpMessagePeekBuffer.size() * 2);
644 }
645
646#if defined (QNATIVESOCKETENGINE_DEBUG)
647 qDebug("QNativeSocketEnginePrivate::nativePendingDatagramSize() == %i", recvResult);
648#endif
649
650 return qint64(recvResult);
651}
652#endif
653qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxSize,
654 QHostAddress *address, quint16 *port)
655{
656 qt_sockaddr aa;
657 memset(&aa, 0, sizeof(aa));
658 QT_SOCKLEN_T sz;
659 sz = sizeof(aa);
660
661 ssize_t recvFromResult = 0;
662#ifdef Q_OS_SYMBIAN
663 char c;
664 recvFromResult = ::recvfrom(socketDescriptor, maxSize ? data : &c, maxSize ? maxSize : 1,
665 0, &aa.a, &sz);
666#else
667 do {
668 char c;
669 recvFromResult = ::recvfrom(socketDescriptor, maxSize ? data : &c, maxSize ? maxSize : 1,
670 0, &aa.a, &sz);
671 } while (recvFromResult == -1 && errno == EINTR);
672#endif
673
674 if (recvFromResult == -1) {
675 setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
676 } else if (port || address) {
677 qt_socket_getPortAndAddress(&aa, port, address);
678 }
679
680#if defined (QNATIVESOCKETENGINE_DEBUG)
681 qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
682 data, qt_prettyDebug(data, qMin(recvFromResult, ssize_t(16)), recvFromResult).data(), maxSize,
683 address ? address->toString().toLatin1().constData() : "(nil)",
684 port ? *port : 0, (qint64) recvFromResult);
685#endif
686
687 return qint64(maxSize ? recvFromResult : recvFromResult == -1 ? -1 : 0);
688}
689
690qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
691 const QHostAddress &host, quint16 port)
692{
693 struct sockaddr_in sockAddrIPv4;
694 struct sockaddr *sockAddrPtr = 0;
695 QT_SOCKLEN_T sockAddrSize = 0;
696
697#if !defined(QT_NO_IPV6)
698 struct sockaddr_in6 sockAddrIPv6;
699 if (host.protocol() == QAbstractSocket::IPv6Protocol) {
700 memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
701 sockAddrIPv6.sin6_family = AF_INET6;
702 sockAddrIPv6.sin6_port = htons(port);
703
704 Q_IPV6ADDR tmp = host.toIPv6Address();
705 memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
706 sockAddrSize = sizeof(sockAddrIPv6);
707 sockAddrPtr = (struct sockaddr *)&sockAddrIPv6;
708 } else
709#endif
710 if (host.protocol() == QAbstractSocket::IPv4Protocol) {
711 memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
712 sockAddrIPv4.sin_family = AF_INET;
713 sockAddrIPv4.sin_port = htons(port);
714 sockAddrIPv4.sin_addr.s_addr = htonl(host.toIPv4Address());
715 sockAddrSize = sizeof(sockAddrIPv4);
716 sockAddrPtr = (struct sockaddr *)&sockAddrIPv4;
717 }
718
719 // ignore the SIGPIPE signal
720 qt_ignore_sigpipe();
721#ifdef Q_OS_SYMBIAN
722 ssize_t sentBytes = ::sendto(socketDescriptor, data, len,
723 0, sockAddrPtr, sockAddrSize);
724#else
725 ssize_t sentBytes = qt_safe_sendto(socketDescriptor, data, len,
726 0, sockAddrPtr, sockAddrSize);
727#endif
728
729 if (sentBytes < 0) {
730 switch (errno) {
731 case EMSGSIZE:
732 setError(QAbstractSocket::DatagramTooLargeError, DatagramTooLargeErrorString);
733 break;
734 default:
735 setError(QAbstractSocket::NetworkError, SendDatagramErrorString);
736 }
737 }
738
739#if defined (QNATIVESOCKETENGINE_DEBUG)
740 qDebug("QNativeSocketEngine::sendDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli", data,
741 qt_prettyDebug(data, qMin<int>(len, 16), len).data(), len, host.toString().toLatin1().constData(),
742 port, (qint64) sentBytes);
743#endif
744
745 return qint64(sentBytes);
746}
747
748bool QNativeSocketEnginePrivate::fetchConnectionParameters()
749{
750 localPort = 0;
751 localAddress.clear();
752 peerPort = 0;
753 peerAddress.clear();
754
755 if (socketDescriptor == -1)
756 return false;
757
758 qt_sockaddr sa;
759 QT_SOCKLEN_T sockAddrSize = sizeof(sa);
760
761 // Determine local address
762 memset(&sa, 0, sizeof(sa));
763 if (::getsockname(socketDescriptor, &sa.a, &sockAddrSize) == 0) {
764 qt_socket_getPortAndAddress(&sa, &localPort, &localAddress);
765
766 // Determine protocol family
767 switch (sa.a.sa_family) {
768 case AF_INET:
769 socketProtocol = QAbstractSocket::IPv4Protocol;
770 break;
771#if !defined (QT_NO_IPV6)
772 case AF_INET6:
773 socketProtocol = QAbstractSocket::IPv6Protocol;
774 break;
775#endif
776 default:
777 socketProtocol = QAbstractSocket::UnknownNetworkLayerProtocol;
778 break;
779 }
780
781 } else if (errno == EBADF) {
782 setError(QAbstractSocket::UnsupportedSocketOperationError, InvalidSocketErrorString);
783 return false;
784 }
785
786 // Determine the remote address
787 if (!::getpeername(socketDescriptor, &sa.a, &sockAddrSize))
788 qt_socket_getPortAndAddress(&sa, &peerPort, &peerAddress);
789
790 // Determine the socket type (UDP/TCP)
791 int value = 0;
792 QT_SOCKOPTLEN_T valueSize = sizeof(int);
793 if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_TYPE, &value, &valueSize) == 0) {
794 if (value == SOCK_STREAM)
795 socketType = QAbstractSocket::TcpSocket;
796 else if (value == SOCK_DGRAM)
797 socketType = QAbstractSocket::UdpSocket;
798 else
799 socketType = QAbstractSocket::UnknownSocketType;
800 }
801#if defined (QNATIVESOCKETENGINE_DEBUG)
802 QString socketProtocolStr = "UnknownProtocol";
803 if (socketProtocol == QAbstractSocket::IPv4Protocol) socketProtocolStr = "IPv4Protocol";
804 else if (socketProtocol == QAbstractSocket::IPv6Protocol) socketProtocolStr = "IPv6Protocol";
805
806 QString socketTypeStr = "UnknownSocketType";
807 if (socketType == QAbstractSocket::TcpSocket) socketTypeStr = "TcpSocket";
808 else if (socketType == QAbstractSocket::UdpSocket) socketTypeStr = "UdpSocket";
809
810 qDebug("QNativeSocketEnginePrivate::fetchConnectionParameters() local == %s:%i,"
811 " peer == %s:%i, socket == %s - %s",
812 localAddress.toString().toLatin1().constData(), localPort,
813 peerAddress.toString().toLatin1().constData(), peerPort,socketTypeStr.toLatin1().constData(),
814 socketProtocolStr.toLatin1().constData());
815#endif
816 return true;
817}
818
819void QNativeSocketEnginePrivate::nativeClose()
820{
821#if defined (QNATIVESOCKETENGINE_DEBUG)
822 qDebug("QNativeSocketEngine::nativeClose()");
823#endif
824
825#ifdef Q_OS_SYMBIAN
826 ::close(socketDescriptor);
827#else
828 qt_safe_close(socketDescriptor);
829#endif
830}
831
832qint64 QNativeSocketEnginePrivate::nativeWrite(const char *data, qint64 len)
833{
834 Q_Q(QNativeSocketEngine);
835
836 // ignore the SIGPIPE signal
837 qt_ignore_sigpipe();
838
839 ssize_t writtenBytes;
840#ifdef Q_OS_SYMBIAN
841 // Symbian does not support signals natively and Open C returns EINTR when moving to offline
842 writtenBytes = ::write(socketDescriptor, data, len);
843#else
844 writtenBytes = qt_safe_write(socketDescriptor, data, len);
845#endif
846
847 if (writtenBytes < 0) {
848 switch (errno) {
849 case EPIPE:
850 case ECONNRESET:
851 writtenBytes = -1;
852 setError(QAbstractSocket::RemoteHostClosedError, RemoteHostClosedErrorString);
853 q->close();
854 break;
855 case EAGAIN:
856 writtenBytes = 0;
857 break;
858 case EMSGSIZE:
859 setError(QAbstractSocket::DatagramTooLargeError, DatagramTooLargeErrorString);
860 break;
861 default:
862 break;
863 }
864 }
865
866#if defined (QNATIVESOCKETENGINE_DEBUG)
867 qDebug("QNativeSocketEnginePrivate::nativeWrite(%p \"%s\", %llu) == %i",
868 data, qt_prettyDebug(data, qMin((int) len, 16),
869 (int) len).data(), len, (int) writtenBytes);
870#endif
871
872 return qint64(writtenBytes);
873}
874/*
875*/
876qint64 QNativeSocketEnginePrivate::nativeRead(char *data, qint64 maxSize)
877{
878 Q_Q(QNativeSocketEngine);
879 if (!q->isValid()) {
880 qWarning("QNativeSocketEngine::unbufferedRead: Invalid socket");
881 return -1;
882 }
883
884 ssize_t r = 0;
885#ifdef Q_OS_SYMBIAN
886 r = ::read(socketDescriptor, data, maxSize);
887#else
888 r = qt_safe_read(socketDescriptor, data, maxSize);
889#endif
890
891 if (r < 0) {
892 r = -1;
893 switch (errno) {
894#if EWOULDBLOCK-0 && EWOULDBLOCK != EAGAIN
895 case EWOULDBLOCK:
896#endif
897 case EAGAIN:
898 // No data was available for reading
899 r = -2;
900 break;
901 case EBADF:
902 case EINVAL:
903 case EIO:
904 //error string is now set in read(), not here in nativeRead()
905 break;
906#ifdef Q_OS_SYMBIAN
907 case EPIPE:
908#endif
909 case ECONNRESET:
910#if defined(Q_OS_VXWORKS)
911 case ESHUTDOWN:
912#endif
913 r = 0;
914 break;
915 default:
916 break;
917 }
918 }
919
920#if defined (QNATIVESOCKETENGINE_DEBUG)
921 qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %llu) == %i",
922 data, qt_prettyDebug(data, qMin(r, ssize_t(16)), r).data(),
923 maxSize, r);
924#endif
925
926 return qint64(r);
927}
928
929int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) const
930{
931 fd_set fds;
932 FD_ZERO(&fds);
933 FD_SET(socketDescriptor, &fds);
934
935 struct timeval tv;
936 tv.tv_sec = timeout / 1000;
937 tv.tv_usec = (timeout % 1000) * 1000;
938
939#ifdef Q_OS_SYMBIAN
940 fd_set fdexception;
941 FD_ZERO(&fdexception);
942 FD_SET(socketDescriptor, &fdexception);
943#endif
944
945 int retval;
946 if (selectForRead)
947#ifdef Q_OS_SYMBIAN
948 retval = ::select(socketDescriptor + 1, &fds, 0, &fdexception, timeout < 0 ? 0 : &tv);
949#else
950 retval = qt_safe_select(socketDescriptor + 1, &fds, 0, 0, timeout < 0 ? 0 : &tv);
951#endif
952 else
953#ifdef Q_OS_SYMBIAN
954 retval = ::select(socketDescriptor + 1, 0, &fds, &fdexception, timeout < 0 ? 0 : &tv);
955#else
956 retval = qt_safe_select(socketDescriptor + 1, 0, &fds, 0, timeout < 0 ? 0 : &tv);
957#endif
958
959
960#ifdef Q_OS_SYMBIAN
961 bool selectForExec = false;
962 if(retval != 0) {
963 if(retval < 0) {
964 qWarning("nativeSelect(....) returned < 0 for socket %d", socketDescriptor);
965 }
966 selectForExec = FD_ISSET(socketDescriptor, &fdexception);
967 }
968 if(selectForExec) {
969 qWarning("nativeSelect (selectForRead %d, retVal %d, errno %d) Unexpected exception for fd %d",
970 selectForRead, retval, errno, socketDescriptor);
971 }
972#endif
973
974 return retval;
975}
976
977int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool checkRead, bool checkWrite,
978 bool *selectForRead, bool *selectForWrite) const
979{
980 fd_set fdread;
981 FD_ZERO(&fdread);
982 if (checkRead)
983 FD_SET(socketDescriptor, &fdread);
984
985 fd_set fdwrite;
986 FD_ZERO(&fdwrite);
987 if (checkWrite)
988 FD_SET(socketDescriptor, &fdwrite);
989
990#ifdef Q_OS_SYMBIAN
991 fd_set fdexception;
992 FD_ZERO(&fdexception);
993 FD_SET(socketDescriptor, &fdexception);
994#endif
995
996 struct timeval tv;
997 tv.tv_sec = timeout / 1000;
998 tv.tv_usec = (timeout % 1000) * 1000;
999
1000 int ret;
1001#ifndef Q_OS_SYMBIAN
1002 ret = qt_safe_select(socketDescriptor + 1, &fdread, &fdwrite, 0, timeout < 0 ? 0 : &tv);
1003#else
1004 QElapsedTimer timer;
1005 timer.start();
1006
1007 do {
1008 ret = ::select(socketDescriptor + 1, &fdread, &fdwrite, &fdexception, timeout < 0 ? 0 : &tv);
1009 bool selectForExec = false;
1010 if(ret != 0) {
1011 if(ret < 0) {
1012 qWarning("nativeSelect(....) returned < 0 for socket %d", socketDescriptor);
1013 }
1014 selectForExec = FD_ISSET(socketDescriptor, &fdexception);
1015 }
1016 if(selectForExec) {
1017 qWarning("nativeSelect (checkRead %d, checkWrite %d, ret %d, errno %d): Unexpected expectfds ready in fd %d",
1018 checkRead, checkWrite, ret, errno, socketDescriptor);
1019 if (checkWrite){
1020 FD_CLR(socketDescriptor, &fdread);
1021 FD_SET(socketDescriptor, &fdwrite);
1022 } else if (checkRead)
1023 FD_SET(socketDescriptor, &fdread);
1024
1025
1026 if ((ret == -1) && ( errno == ECONNREFUSED || errno == EPIPE ))
1027 ret = 1;
1028
1029 }
1030
1031 if (ret != -1 || errno != EINTR) {
1032 break;
1033 }
1034
1035 if (timeout > 0) {
1036 // recalculate the timeout
1037 int t = timeout - timer.elapsed();
1038 if (t < 0) {
1039 // oops, timeout turned negative?
1040 ret = -1;
1041 break;
1042 }
1043
1044 tv.tv_sec = t / 1000;
1045 tv.tv_usec = (t % 1000) * 1000;
1046 }
1047 } while (true);
1048#endif
1049
1050 if (ret <= 0)
1051 return ret;
1052 *selectForRead = FD_ISSET(socketDescriptor, &fdread);
1053 *selectForWrite = FD_ISSET(socketDescriptor, &fdwrite);
1054
1055 return ret;
1056}
1057
1058QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.