VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/socket.cpp@ 70481

Last change on this file since 70481 was 70481, checked in by vboxsync, 7 years ago

iprt/socket,tcp,pollset: Added RTTcpCreatePair. Implemented polling fallback for winsock 1.x. Extended tstRTPoll to cover sockets and actual waiting and receiving of events on pipe & socket events.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 91.6 KB
Line 
1/* $Id: socket.cpp 70481 2018-01-07 18:46:08Z vboxsync $ */
2/** @file
3 * IPRT - Network Sockets.
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <iprt/win/winsock2.h>
33# include <iprt/win/ws2tcpip.h>
34#else /* !RT_OS_WINDOWS */
35# include <errno.h>
36# include <sys/select.h>
37# include <sys/stat.h>
38# include <sys/socket.h>
39# include <netinet/in.h>
40# include <netinet/tcp.h>
41# include <arpa/inet.h>
42# ifdef IPRT_WITH_TCPIP_V6
43# include <netinet6/in6.h>
44# endif
45# include <sys/un.h>
46# include <netdb.h>
47# include <unistd.h>
48# include <fcntl.h>
49# include <sys/uio.h>
50#endif /* !RT_OS_WINDOWS */
51#include <limits.h>
52
53#include "internal/iprt.h"
54#include <iprt/socket.h>
55
56#include <iprt/alloca.h>
57#include <iprt/asm.h>
58#include <iprt/assert.h>
59#include <iprt/ctype.h>
60#include <iprt/err.h>
61#include <iprt/mempool.h>
62#include <iprt/poll.h>
63#include <iprt/string.h>
64#include <iprt/thread.h>
65#include <iprt/time.h>
66#include <iprt/mem.h>
67#include <iprt/sg.h>
68#include <iprt/log.h>
69
70#include "internal/magics.h"
71#include "internal/socket.h"
72#include "internal/string.h"
73#ifdef RT_OS_WINDOWS
74# include "win/internal-r3-win.h"
75#endif
76
77
78/*********************************************************************************************************************************
79* Defined Constants And Macros *
80*********************************************************************************************************************************/
81/* non-standard linux stuff (it seems). */
82#ifndef MSG_NOSIGNAL
83# define MSG_NOSIGNAL 0
84#endif
85
86/* Windows has different names for SHUT_XXX. */
87#ifndef SHUT_RDWR
88# ifdef SD_BOTH
89# define SHUT_RDWR SD_BOTH
90# else
91# define SHUT_RDWR 2
92# endif
93#endif
94#ifndef SHUT_WR
95# ifdef SD_SEND
96# define SHUT_WR SD_SEND
97# else
98# define SHUT_WR 1
99# endif
100#endif
101#ifndef SHUT_RD
102# ifdef SD_RECEIVE
103# define SHUT_RD SD_RECEIVE
104# else
105# define SHUT_RD 0
106# endif
107#endif
108
109/* fixup backlevel OSes. */
110#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
111# define socklen_t int
112#endif
113
114/** How many pending connection. */
115#define RTTCP_SERVER_BACKLOG 10
116
117/* Limit read and write sizes on Windows and OS/2. */
118#ifdef RT_OS_WINDOWS
119# define RTSOCKET_MAX_WRITE (INT_MAX / 2)
120# define RTSOCKET_MAX_READ (INT_MAX / 2)
121#elif defined(RT_OS_OS2)
122# define RTSOCKET_MAX_WRITE 0x10000
123# define RTSOCKET_MAX_READ 0x10000
124#endif
125
126
127/*********************************************************************************************************************************
128* Structures and Typedefs *
129*********************************************************************************************************************************/
130/**
131 * Socket handle data.
132 *
133 * This is mainly required for implementing RTPollSet on Windows.
134 */
135typedef struct RTSOCKETINT
136{
137 /** Magic number (RTSOCKET_MAGIC). */
138 uint32_t u32Magic;
139 /** Exclusive user count.
140 * This is used to prevent two threads from accessing the handle concurrently.
141 * It can be higher than 1 if this handle is reference multiple times in a
142 * polling set (Windows). */
143 uint32_t volatile cUsers;
144 /** The native socket handle. */
145 RTSOCKETNATIVE hNative;
146 /** Indicates whether the handle has been closed or not. */
147 bool volatile fClosed;
148 /** Indicates whether the socket is operating in blocking or non-blocking mode
149 * currently. */
150 bool fBlocking;
151#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
152 /** The pollset currently polling this socket. This is NIL if no one is
153 * polling. */
154 RTPOLLSET hPollSet;
155#endif
156#ifdef RT_OS_WINDOWS
157 /** The event semaphore we've associated with the socket handle.
158 * This is WSA_INVALID_EVENT if not done. */
159 WSAEVENT hEvent;
160 /** The events we're polling for. */
161 uint32_t fPollEvts;
162 /** The events we're currently subscribing to with WSAEventSelect.
163 * This is ZERO if we're currently not subscribing to anything. */
164 uint32_t fSubscribedEvts;
165 /** Saved events which are only posted once. */
166 uint32_t fEventsSaved;
167 /** Set if we're using the polling fallback. */
168 bool fPollFallback;
169 /** Set if the fallback polling is active (event not set). */
170 bool volatile fPollFallbackActive;
171 /** Set to shut down the fallback polling thread. */
172 bool volatile fPollFallbackShutdown;
173 /** Socket use to wake up the select thread. */
174 RTSOCKETNATIVE hPollFallbackNotifyW;
175 /** Socket the select thread always waits on. */
176 RTSOCKETNATIVE hPollFallbackNotifyR;
177 /** The fallback polling thread. */
178 RTTHREAD hPollFallbackThread;
179#endif /* RT_OS_WINDOWS */
180} RTSOCKETINT;
181
182
183/**
184 * Address union used internally for things like getpeername and getsockname.
185 */
186typedef union RTSOCKADDRUNION
187{
188 struct sockaddr Addr;
189 struct sockaddr_in IPv4;
190#ifdef IPRT_WITH_TCPIP_V6
191 struct sockaddr_in6 IPv6;
192#endif
193} RTSOCKADDRUNION;
194
195
196/*********************************************************************************************************************************
197* Global Variables *
198*********************************************************************************************************************************/
199#ifdef RT_OS_WINDOWS
200/** Indicates that we've successfully initialized winsock. */
201static uint32_t volatile g_uWinSockInitedVersion = 0;
202#endif
203
204
205/*********************************************************************************************************************************
206* Internal Functions *
207*********************************************************************************************************************************/
208#ifdef RT_OS_WINDOWS
209static void rtSocketPokePollFallbackThread(RTSOCKETINT *pThis);
210#endif
211
212
213
214#ifdef RT_OS_WINDOWS
215/**
216 * Initializes winsock for the process.
217 *
218 * @returns IPRT status code.
219 */
220static int rtSocketInitWinsock(void)
221{
222 if (g_uWinSockInitedVersion != 0)
223 return VINF_SUCCESS;
224
225 if ( !g_pfnWSAGetLastError
226 || !g_pfnWSAStartup
227 || !g_pfnsocket
228 || !g_pfnclosesocket)
229 return VERR_NET_INIT_FAILED;
230
231 /*
232 * Initialize winsock. Try with 2.2 and back down till we get something that works.
233 */
234 static const WORD s_awVersions[] =
235 {
236 MAKEWORD(2, 2),
237 MAKEWORD(2, 1),
238 MAKEWORD(2, 0),
239 MAKEWORD(1, 1),
240 MAKEWORD(1, 0),
241 };
242 for (uint32_t i = 0; i < RT_ELEMENTS(s_awVersions); i++)
243 {
244 WSADATA wsaData;
245 RT_ZERO(wsaData);
246 int rcWsa = g_pfnWSAStartup(s_awVersions[i], &wsaData);
247 if (rcWsa == 0)
248 {
249 /* AssertMsg(wsaData.wVersion >= s_awVersions[i]); - triggers with winsock 1.1 */
250 ASMAtomicWriteU32(&g_uWinSockInitedVersion, wsaData.wVersion);
251 return VINF_SUCCESS;
252 }
253 AssertLogRelMsg(rcWsa == WSAVERNOTSUPPORTED, ("rcWsa=%d (winsock version %#x)\n", rcWsa, s_awVersions[i]));
254 }
255 LogRel(("Failed to init winsock!\n"));
256 return VERR_NET_INIT_FAILED;
257}
258#endif
259
260
261/**
262 * Get the last error as an iprt status code.
263 *
264 * @returns IPRT status code.
265 */
266DECLINLINE(int) rtSocketError(void)
267{
268#ifdef RT_OS_WINDOWS
269 if (g_pfnWSAGetLastError)
270 return RTErrConvertFromWin32(g_pfnWSAGetLastError());
271 return VERR_NET_IO_ERROR;
272#else
273 return RTErrConvertFromErrno(errno);
274#endif
275}
276
277
278/**
279 * Resets the last error.
280 */
281DECLINLINE(void) rtSocketErrorReset(void)
282{
283#ifdef RT_OS_WINDOWS
284 if (g_pfnWSASetLastError)
285 g_pfnWSASetLastError(0);
286#else
287 errno = 0;
288#endif
289}
290
291
292/**
293 * Get the last resolver error as an iprt status code.
294 *
295 * @returns iprt status code.
296 */
297DECLHIDDEN(int) rtSocketResolverError(void)
298{
299#ifdef RT_OS_WINDOWS
300 if (g_pfnWSAGetLastError)
301 return RTErrConvertFromWin32(g_pfnWSAGetLastError());
302 return VERR_UNRESOLVED_ERROR;
303#else
304 switch (h_errno)
305 {
306 case HOST_NOT_FOUND:
307 return VERR_NET_HOST_NOT_FOUND;
308 case NO_DATA:
309 return VERR_NET_ADDRESS_NOT_AVAILABLE;
310 case NO_RECOVERY:
311 return VERR_IO_GEN_FAILURE;
312 case TRY_AGAIN:
313 return VERR_TRY_AGAIN;
314
315 default:
316 AssertLogRelMsgFailed(("Unhandled error %u\n", h_errno));
317 return VERR_UNRESOLVED_ERROR;
318 }
319#endif
320}
321
322
323/**
324 * Converts from a native socket address to a generic IPRT network address.
325 *
326 * @returns IPRT status code.
327 * @param pSrc The source address.
328 * @param cbSrc The size of the source address.
329 * @param pAddr Where to return the generic IPRT network
330 * address.
331 */
332static int rtSocketNetAddrFromAddr(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
333{
334 /*
335 * Convert the address.
336 */
337 if ( cbSrc == sizeof(struct sockaddr_in)
338 && pSrc->Addr.sa_family == AF_INET)
339 {
340 RT_ZERO(*pAddr);
341 pAddr->enmType = RTNETADDRTYPE_IPV4;
342 pAddr->uPort = RT_N2H_U16(pSrc->IPv4.sin_port);
343 pAddr->uAddr.IPv4.u = pSrc->IPv4.sin_addr.s_addr;
344 }
345#ifdef IPRT_WITH_TCPIP_V6
346 else if ( cbSrc == sizeof(struct sockaddr_in6)
347 && pSrc->Addr.sa_family == AF_INET6)
348 {
349 RT_ZERO(*pAddr);
350 pAddr->enmType = RTNETADDRTYPE_IPV6;
351 pAddr->uPort = RT_N2H_U16(pSrc->IPv6.sin6_port);
352 pAddr->uAddr.IPv6.au32[0] = pSrc->IPv6.sin6_addr.s6_addr32[0];
353 pAddr->uAddr.IPv6.au32[1] = pSrc->IPv6.sin6_addr.s6_addr32[1];
354 pAddr->uAddr.IPv6.au32[2] = pSrc->IPv6.sin6_addr.s6_addr32[2];
355 pAddr->uAddr.IPv6.au32[3] = pSrc->IPv6.sin6_addr.s6_addr32[3];
356 }
357#endif
358 else
359 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
360 return VINF_SUCCESS;
361}
362
363
364/**
365 * Converts from a generic IPRT network address to a native socket address.
366 *
367 * @returns IPRT status code.
368 * @param pAddr Pointer to the generic IPRT network address.
369 * @param pDst The source address.
370 * @param cbDst The size of the source address.
371 * @param pcbAddr Where to store the size of the returned address.
372 * Optional
373 */
374static int rtSocketAddrFromNetAddr(PCRTNETADDR pAddr, RTSOCKADDRUNION *pDst, size_t cbDst, int *pcbAddr)
375{
376 RT_BZERO(pDst, cbDst);
377 if ( pAddr->enmType == RTNETADDRTYPE_IPV4
378 && cbDst >= sizeof(struct sockaddr_in))
379 {
380 pDst->Addr.sa_family = AF_INET;
381 pDst->IPv4.sin_port = RT_H2N_U16(pAddr->uPort);
382 pDst->IPv4.sin_addr.s_addr = pAddr->uAddr.IPv4.u;
383 if (pcbAddr)
384 *pcbAddr = sizeof(pDst->IPv4);
385 }
386#ifdef IPRT_WITH_TCPIP_V6
387 else if ( pAddr->enmType == RTNETADDRTYPE_IPV6
388 && cbDst >= sizeof(struct sockaddr_in6))
389 {
390 pDst->Addr.sa_family = AF_INET6;
391 pDst->IPv6.sin6_port = RT_H2N_U16(pAddr->uPort);
392 pSrc->IPv6.sin6_addr.s6_addr32[0] = pAddr->uAddr.IPv6.au32[0];
393 pSrc->IPv6.sin6_addr.s6_addr32[1] = pAddr->uAddr.IPv6.au32[1];
394 pSrc->IPv6.sin6_addr.s6_addr32[2] = pAddr->uAddr.IPv6.au32[2];
395 pSrc->IPv6.sin6_addr.s6_addr32[3] = pAddr->uAddr.IPv6.au32[3];
396 if (pcbAddr)
397 *pcbAddr = sizeof(pDst->IPv6);
398 }
399#endif
400 else
401 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
402 return VINF_SUCCESS;
403}
404
405
406/**
407 * Tries to lock the socket for exclusive usage by the calling thread.
408 *
409 * Call rtSocketUnlock() to unlock.
410 *
411 * @returns @c true if locked, @c false if not.
412 * @param pThis The socket structure.
413 */
414DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
415{
416 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
417}
418
419
420/**
421 * Unlocks the socket.
422 *
423 * @param pThis The socket structure.
424 */
425DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
426{
427 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
428}
429
430
431/**
432 * The slow path of rtSocketSwitchBlockingMode that does the actual switching.
433 *
434 * @returns IPRT status code.
435 * @param pThis The socket structure.
436 * @param fBlocking The desired mode of operation.
437 * @remarks Do not call directly.
438 */
439static int rtSocketSwitchBlockingModeSlow(RTSOCKETINT *pThis, bool fBlocking)
440{
441#ifdef RT_OS_WINDOWS
442 AssertReturn(g_pfnioctlsocket, VERR_NET_NOT_UNSUPPORTED);
443 u_long uBlocking = fBlocking ? 0 : 1;
444 if (g_pfnioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
445 return rtSocketError();
446
447#else
448 int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
449 if (fFlags == -1)
450 return rtSocketError();
451
452 if (fBlocking)
453 fFlags &= ~O_NONBLOCK;
454 else
455 fFlags |= O_NONBLOCK;
456 if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
457 return rtSocketError();
458#endif
459
460 pThis->fBlocking = fBlocking;
461 return VINF_SUCCESS;
462}
463
464
465/**
466 * Switches the socket to the desired blocking mode if necessary.
467 *
468 * The socket must be locked.
469 *
470 * @returns IPRT status code.
471 * @param pThis The socket structure.
472 * @param fBlocking The desired mode of operation.
473 */
474DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
475{
476 if (pThis->fBlocking != fBlocking)
477 return rtSocketSwitchBlockingModeSlow(pThis, fBlocking);
478 return VINF_SUCCESS;
479}
480
481
482/**
483 * Creates an IPRT socket handle for a native one.
484 *
485 * @returns IPRT status code.
486 * @param ppSocket Where to return the IPRT socket handle.
487 * @param hNative The native handle.
488 */
489DECLHIDDEN(int) rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
490{
491 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
492 if (!pThis)
493 return VERR_NO_MEMORY;
494 pThis->u32Magic = RTSOCKET_MAGIC;
495 pThis->cUsers = 0;
496 pThis->hNative = hNative;
497 pThis->fClosed = false;
498 pThis->fBlocking = true;
499#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
500 pThis->hPollSet = NIL_RTPOLLSET;
501#endif
502#ifdef RT_OS_WINDOWS
503 pThis->hEvent = WSA_INVALID_EVENT;
504 pThis->fPollEvts = 0;
505 pThis->fSubscribedEvts = 0;
506 pThis->fEventsSaved = 0;
507 pThis->fPollFallback = g_uWinSockInitedVersion < MAKEWORD(2, 0)
508 || g_pfnWSACreateEvent == NULL
509 || g_pfnWSACloseEvent == NULL
510 || g_pfnWSAEventSelect == NULL
511 || g_pfnWSAEnumNetworkEvents == NULL;
512 pThis->fPollFallbackActive = false;
513 pThis->fPollFallbackShutdown = false;
514 pThis->hPollFallbackNotifyR = NIL_RTSOCKETNATIVE;
515 pThis->hPollFallbackNotifyW = NIL_RTSOCKETNATIVE;
516 pThis->hPollFallbackThread = NIL_RTTHREAD;
517#endif
518 *ppSocket = pThis;
519 return VINF_SUCCESS;
520}
521
522
523RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
524{
525 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
526#ifndef RT_OS_WINDOWS
527 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
528#endif
529 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
530 return rtSocketCreateForNative(phSocket, uNative);
531}
532
533
534/**
535 * Wrapper around socket().
536 *
537 * @returns IPRT status code.
538 * @param phSocket Where to store the handle to the socket on
539 * success.
540 * @param iDomain The protocol family (PF_XXX).
541 * @param iType The socket type (SOCK_XXX).
542 * @param iProtocol Socket parameter, usually 0.
543 */
544DECLHIDDEN(int) rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
545{
546#ifdef RT_OS_WINDOWS
547 AssertReturn(g_pfnsocket, VERR_NET_NOT_UNSUPPORTED);
548 AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
549
550 /* Initialize WinSock. */
551 int rc2 = rtSocketInitWinsock();
552 if (RT_FAILURE(rc2))
553 return rc2;
554#endif
555
556 /*
557 * Create the socket.
558 */
559#ifdef RT_OS_WINDOWS
560 RTSOCKETNATIVE hNative = g_pfnsocket(iDomain, iType, iProtocol);
561#else
562 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
563#endif
564 if (hNative == NIL_RTSOCKETNATIVE)
565 return rtSocketError();
566
567 /*
568 * Wrap it.
569 */
570 int rc = rtSocketCreateForNative(phSocket, hNative);
571 if (RT_FAILURE(rc))
572 {
573#ifdef RT_OS_WINDOWS
574 g_pfnclosesocket(hNative);
575#else
576 close(hNative);
577#endif
578 }
579 return rc;
580}
581
582
583/**
584 * Wrapper around socketpair() for creating a local TCP connection.
585 *
586 * @returns IPRT status code.
587 * @param phServer Where to return the first native socket.
588 * @param phClient Where to return the second native socket.
589 */
590static int rtSocketCreateNativeTcpPair(RTSOCKETNATIVE *phServer, RTSOCKETNATIVE *phClient)
591{
592#ifdef RT_OS_WINDOWS
593 /*
594 * Initialize WinSock and make sure we got the necessary APIs.
595 */
596 int rc = rtSocketInitWinsock();
597 if (RT_FAILURE(rc))
598 return rc;
599 AssertReturn(g_pfnsocket, VERR_NET_NOT_UNSUPPORTED);
600 AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
601 AssertReturn(g_pfnsetsockopt, VERR_NET_NOT_UNSUPPORTED);
602 AssertReturn(g_pfnbind, VERR_NET_NOT_UNSUPPORTED);
603 AssertReturn(g_pfngetsockname, VERR_NET_NOT_UNSUPPORTED);
604 AssertReturn(g_pfnlisten, VERR_NET_NOT_UNSUPPORTED);
605 AssertReturn(g_pfnaccept, VERR_NET_NOT_UNSUPPORTED);
606 AssertReturn(g_pfnconnect, VERR_NET_NOT_UNSUPPORTED);
607
608 /*
609 * Create the "server" listen socket and the "client" socket.
610 */
611 RTSOCKETNATIVE hListener = g_pfnsocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
612 if (hListener == NIL_RTSOCKETNATIVE)
613 return rtSocketError();
614 RTSOCKETNATIVE hClient = g_pfnsocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
615 if (hClient != NIL_RTSOCKETNATIVE)
616 {
617
618 /*
619 * We let WinSock choose a port number when we bind.
620 */
621 union
622 {
623 struct sockaddr_in Ip;
624 struct sockaddr Generic;
625 } uAddr;
626 RT_ZERO(uAddr);
627 uAddr.Ip.sin_family = AF_INET;
628 uAddr.Ip.sin_addr.s_addr = RT_H2N_U32_C(INADDR_LOOPBACK);
629 //uAddr.Ip.sin_port = 0;
630 int fReuse = 1;
631 rc = g_pfnsetsockopt(hListener, SOL_SOCKET, SO_REUSEADDR, (const char *)&fReuse, sizeof(fReuse));
632 if (rc == 0)
633 {
634 rc = g_pfnbind(hListener, &uAddr.Generic, sizeof(uAddr.Ip));
635 if (rc == 0)
636 {
637 /*
638 * Get the address the client should connect to. According to the docs,
639 * we cannot assume that getsockname sets the IP and family.
640 */
641 RT_ZERO(uAddr);
642 int cbAddr = sizeof(uAddr.Ip);
643 rc = g_pfngetsockname(hListener, &uAddr.Generic, &cbAddr);
644 if (rc == 0)
645 {
646 uAddr.Ip.sin_family = AF_INET;
647 uAddr.Ip.sin_addr.s_addr = RT_H2N_U32_C(INADDR_LOOPBACK);
648
649 /*
650 * Listen, connect and accept.
651 */
652 rc = g_pfnlisten(hListener, 1 /*cBacklog*/);
653 if (rc == 0)
654 {
655 rc = g_pfnconnect(hClient, &uAddr.Generic, sizeof(uAddr.Ip));
656 if (rc == 0)
657 {
658 RTSOCKETNATIVE hServer = g_pfnaccept(hListener, NULL, NULL);
659 if (hServer != NIL_RTSOCKETNATIVE)
660 {
661 g_pfnclosesocket(hListener);
662
663 /*
664 * Done!
665 */
666 *phServer = hServer;
667 *phClient = hClient;
668 return VINF_SUCCESS;
669 }
670 }
671 }
672 }
673 }
674 }
675 rc = rtSocketError();
676 g_pfnclosesocket(hClient);
677 }
678 else
679 rc = rtSocketError();
680 g_pfnclosesocket(hListener);
681 return rc;
682
683#else
684 /*
685 * Got socket pair, so use it.
686 */
687 int aSockets[2] = { -1, -1 };
688 int (socketpair(AF_INET, SOCK_STREAM, IPPROTO_TCP, aSockets) == 0)
689 {
690 *phServer = aSockets[0];
691 *phClient = aSockets[0];
692 return VINF_SUCCESS;
693 }
694 return rtSocketError();
695#endif
696}
697
698
699/**
700 * Worker for RTTcpCreatePair.
701 *
702 * @returns IPRT status code.
703 * @param phServer Where to return the "server" side of the pair.
704 * @param phClient Where to return the "client" side of the pair.
705 * @note There is no server or client side, but we gotta call it something.
706 */
707DECLHIDDEN(int) rtSocketCreateTcpPair(RTSOCKET *phServer, RTSOCKET *phClient)
708{
709 RTSOCKETNATIVE hServer = NIL_RTSOCKETNATIVE;
710 RTSOCKETNATIVE hClient = NIL_RTSOCKETNATIVE;
711 int rc = rtSocketCreateNativeTcpPair(&hServer, &hClient);
712 if (RT_SUCCESS(rc))
713 {
714 rc = rtSocketCreateForNative(phServer, hServer);
715 if (RT_SUCCESS(rc))
716 {
717 rc = rtSocketCreateForNative(phClient, hClient);
718 if (RT_SUCCESS(rc))
719 return VINF_SUCCESS;
720 RTSocketRelease(*phServer);
721 }
722 else
723 {
724#ifdef RT_OS_WINDOWS
725 g_pfnclosesocket(hServer);
726#else
727 close(hServer);
728#endif
729 }
730#ifdef RT_OS_WINDOWS
731 g_pfnclosesocket(hClient);
732#else
733 close(hClient);
734#endif
735 }
736
737 *phServer = NIL_RTSOCKET;
738 *phClient = NIL_RTSOCKET;
739 return rc;
740}
741
742
743RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
744{
745 RTSOCKETINT *pThis = hSocket;
746 AssertPtrReturn(pThis, UINT32_MAX);
747 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
748 return RTMemPoolRetain(pThis);
749}
750
751
752/**
753 * Worker for RTSocketRelease and RTSocketClose.
754 *
755 * @returns IPRT status code.
756 * @param pThis The socket handle instance data.
757 * @param fDestroy Whether we're reaching ref count zero.
758 */
759static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
760{
761 /*
762 * Invalidate the handle structure on destroy.
763 */
764 if (fDestroy)
765 {
766 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
767 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
768 }
769
770 int rc = VINF_SUCCESS;
771 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
772 {
773#ifdef RT_OS_WINDOWS
774 /*
775 * Poke the polling thread if active and give it a small chance to stop.
776 */
777 if ( pThis->fPollFallback
778 && pThis->hPollFallbackThread != NIL_RTTHREAD)
779 {
780 ASMAtomicWriteBool(&pThis->fPollFallbackShutdown, true);
781 rtSocketPokePollFallbackThread(pThis);
782 int rc2 = RTThreadWait(pThis->hPollFallbackThread, RT_MS_1SEC, NULL);
783 if (RT_SUCCESS(rc2))
784 pThis->hPollFallbackThread = NIL_RTTHREAD;
785 }
786#endif
787
788 /*
789 * Close the native handle.
790 */
791 RTSOCKETNATIVE hNative = pThis->hNative;
792 if (hNative != NIL_RTSOCKETNATIVE)
793 {
794 pThis->hNative = NIL_RTSOCKETNATIVE;
795
796#ifdef RT_OS_WINDOWS
797 AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
798 if (g_pfnclosesocket(hNative))
799#else
800 if (close(hNative))
801#endif
802 {
803 rc = rtSocketError();
804#ifdef RT_OS_WINDOWS
805 AssertMsgFailed(("closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
806#else
807 AssertMsgFailed(("close(%d) -> %Rrc\n", hNative, rc));
808#endif
809 }
810 }
811
812#ifdef RT_OS_WINDOWS
813 /*
814 * Windows specific polling cleanup.
815 */
816 WSAEVENT hEvent = pThis->hEvent;
817 if (hEvent != WSA_INVALID_EVENT)
818 {
819 pThis->hEvent = WSA_INVALID_EVENT;
820 if (!pThis->fPollFallback)
821 {
822 Assert(g_pfnWSACloseEvent);
823 if (g_pfnWSACloseEvent)
824 g_pfnWSACloseEvent(hEvent);
825 }
826 else
827 CloseHandle(hEvent);
828 }
829
830 if (pThis->fPollFallback)
831 {
832 if (pThis->hPollFallbackNotifyW != NIL_RTSOCKETNATIVE)
833 {
834 g_pfnclosesocket(pThis->hPollFallbackNotifyW);
835 pThis->hPollFallbackNotifyW = NIL_RTSOCKETNATIVE;
836 }
837
838 if (pThis->hPollFallbackThread != NIL_RTTHREAD)
839 {
840 int rc2 = RTThreadWait(pThis->hPollFallbackThread, RT_MS_1MIN / 2, NULL);
841 AssertRC(rc2);
842 pThis->hPollFallbackThread = NIL_RTTHREAD;
843 }
844
845 if (pThis->hPollFallbackNotifyR != NIL_RTSOCKETNATIVE)
846 {
847 g_pfnclosesocket(pThis->hPollFallbackNotifyR);
848 pThis->hPollFallbackNotifyR = NIL_RTSOCKETNATIVE;
849 }
850 }
851#endif
852 }
853
854 return rc;
855}
856
857
858RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
859{
860 RTSOCKETINT *pThis = hSocket;
861 if (pThis == NIL_RTSOCKET)
862 return 0;
863 AssertPtrReturn(pThis, UINT32_MAX);
864 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
865
866 /* get the refcount without killing it... */
867 uint32_t cRefs = RTMemPoolRefCount(pThis);
868 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
869 if (cRefs == 1)
870 rtSocketCloseIt(pThis, true);
871
872 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
873}
874
875
876RTDECL(int) RTSocketClose(RTSOCKET hSocket)
877{
878 RTSOCKETINT *pThis = hSocket;
879 if (pThis == NIL_RTSOCKET)
880 return VINF_SUCCESS;
881 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
882 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
883
884 uint32_t cRefs = RTMemPoolRefCount(pThis);
885 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
886
887 int rc = rtSocketCloseIt(pThis, cRefs == 1);
888
889 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
890 return rc;
891}
892
893
894RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
895{
896 RTSOCKETINT *pThis = hSocket;
897 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
898 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
899 return (RTHCUINTPTR)pThis->hNative;
900}
901
902
903RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
904{
905 RTSOCKETINT *pThis = hSocket;
906 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
907 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
908 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
909
910 int rc = VINF_SUCCESS;
911#ifdef RT_OS_WINDOWS
912 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
913 rc = RTErrConvertFromWin32(GetLastError());
914#else
915 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
916 rc = RTErrConvertFromErrno(errno);
917#endif
918
919 return rc;
920}
921
922
923static bool rtSocketIsIPv4Numerical(const char *pszAddress, PRTNETADDRIPV4 pAddr)
924{
925
926 /* Empty address resolves to the INADDR_ANY address (good for bind). */
927 if (!pszAddress || !*pszAddress)
928 {
929 pAddr->u = INADDR_ANY;
930 return true;
931 }
932
933 /* Four quads? */
934 char *psz = (char *)pszAddress;
935 for (int i = 0; i < 4; i++)
936 {
937 uint8_t u8;
938 int rc = RTStrToUInt8Ex(psz, &psz, 0, &u8);
939 if (rc != VINF_SUCCESS && rc != VWRN_TRAILING_CHARS)
940 return false;
941 if (*psz != (i < 3 ? '.' : '\0'))
942 return false;
943 psz++;
944
945 pAddr->au8[i] = u8; /* big endian */
946 }
947
948 return true;
949}
950
951RTDECL(int) RTSocketParseInetAddress(const char *pszAddress, unsigned uPort, PRTNETADDR pAddr)
952{
953 int rc;
954
955 /*
956 * Validate input.
957 */
958 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
959 AssertPtrNullReturn(pszAddress, VERR_INVALID_POINTER);
960
961 /*
962 * Resolve the address. Pretty crude at the moment, but we have to make
963 * sure to not ask the NT 4 gethostbyname about an IPv4 address as it may
964 * give a wrong answer.
965 */
966 /** @todo this only supports IPv4, and IPv6 support needs to be added.
967 * It probably needs to be converted to getaddrinfo(). */
968 RTNETADDRIPV4 IPv4Quad;
969 if (rtSocketIsIPv4Numerical(pszAddress, &IPv4Quad))
970 {
971 Log3(("rtSocketIsIPv4Numerical: %s -> %#x (%RTnaipv4)\n", pszAddress, IPv4Quad.u, IPv4Quad));
972 RT_ZERO(*pAddr);
973 pAddr->enmType = RTNETADDRTYPE_IPV4;
974 pAddr->uPort = uPort;
975 pAddr->uAddr.IPv4 = IPv4Quad;
976 return VINF_SUCCESS;
977 }
978
979#ifdef RT_OS_WINDOWS
980 /* Initialize WinSock and check version before we call gethostbyname. */
981 if (!g_pfngethostbyname)
982 return VERR_NET_NOT_UNSUPPORTED;
983
984 int rc2 = rtSocketInitWinsock();
985 if (RT_FAILURE(rc2))
986 return rc2;
987
988# define gethostbyname g_pfngethostbyname
989#endif
990
991 struct hostent *pHostEnt;
992 pHostEnt = gethostbyname(pszAddress);
993 if (!pHostEnt)
994 {
995 rc = rtSocketResolverError();
996 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
997 return rc;
998 }
999
1000 if (pHostEnt->h_addrtype == AF_INET)
1001 {
1002 RT_ZERO(*pAddr);
1003 pAddr->enmType = RTNETADDRTYPE_IPV4;
1004 pAddr->uPort = uPort;
1005 pAddr->uAddr.IPv4.u = ((struct in_addr *)pHostEnt->h_addr)->s_addr;
1006 Log3(("gethostbyname: %s -> %#x (%RTnaipv4)\n", pszAddress, pAddr->uAddr.IPv4.u, pAddr->uAddr.IPv4));
1007 }
1008 else
1009 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1010
1011#ifdef RT_OS_WINDOWS
1012# undef gethostbyname
1013#endif
1014 return VINF_SUCCESS;
1015}
1016
1017
1018/*
1019 * New function to allow both ipv4 and ipv6 addresses to be resolved.
1020 * Breaks compatibility with windows before 2000.
1021 */
1022RTDECL(int) RTSocketQueryAddressStr(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
1023{
1024 AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
1025 AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
1026 AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
1027 AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);
1028
1029#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
1030 return VERR_NOT_SUPPORTED;
1031
1032#else
1033 int rc;
1034 if (*pcbResult < 16)
1035 return VERR_NET_ADDRESS_NOT_AVAILABLE;
1036
1037 /* Setup the hint. */
1038 struct addrinfo grHints;
1039 RT_ZERO(grHints);
1040 grHints.ai_socktype = 0;
1041 grHints.ai_flags = 0;
1042 grHints.ai_protocol = 0;
1043 grHints.ai_family = AF_UNSPEC;
1044 if (penmAddrType)
1045 {
1046 switch (*penmAddrType)
1047 {
1048 case RTNETADDRTYPE_INVALID:
1049 /*grHints.ai_family = AF_UNSPEC;*/
1050 break;
1051 case RTNETADDRTYPE_IPV4:
1052 grHints.ai_family = AF_INET;
1053 break;
1054 case RTNETADDRTYPE_IPV6:
1055 grHints.ai_family = AF_INET6;
1056 break;
1057 default:
1058 AssertFailedReturn(VERR_INVALID_PARAMETER);
1059 }
1060 }
1061
1062# ifdef RT_OS_WINDOWS
1063 /*
1064 * Winsock2 init
1065 */
1066 if ( !g_pfngetaddrinfo
1067 || !g_pfnfreeaddrinfo)
1068 return VERR_NET_NOT_UNSUPPORTED;
1069
1070 int rc2 = rtSocketInitWinsock();
1071 if (RT_FAILURE(rc2))
1072 return rc2;
1073
1074# define getaddrinfo g_pfngetaddrinfo
1075# define freeaddrinfo g_pfnfreeaddrinfo
1076# endif
1077
1078 /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
1079 struct addrinfo *pgrResults = NULL;
1080 rc = getaddrinfo(pszHost, "", &grHints, &pgrResults);
1081 if (rc != 0)
1082 return VERR_NET_ADDRESS_NOT_AVAILABLE;
1083
1084 // return data
1085 // on multiple matches return only the first one
1086
1087 if (!pgrResults)
1088 return VERR_NET_ADDRESS_NOT_AVAILABLE;
1089
1090 struct addrinfo const *pgrResult = pgrResults->ai_next;
1091 if (!pgrResult)
1092 {
1093 freeaddrinfo(pgrResults);
1094 return VERR_NET_ADDRESS_NOT_AVAILABLE;
1095 }
1096
1097 RTNETADDRTYPE enmAddrType = RTNETADDRTYPE_INVALID;
1098 size_t cchIpAddress;
1099 char szIpAddress[48];
1100 if (pgrResult->ai_family == AF_INET)
1101 {
1102 struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
1103 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
1104 "%RTnaipv4", pgrSa->sin_addr.s_addr);
1105 Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
1106 enmAddrType = RTNETADDRTYPE_IPV4;
1107 rc = VINF_SUCCESS;
1108 }
1109 else if (pgrResult->ai_family == AF_INET6)
1110 {
1111 struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
1112 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
1113 "%RTnaipv6", (PRTNETADDRIPV6)&pgrSa6->sin6_addr);
1114 enmAddrType = RTNETADDRTYPE_IPV6;
1115 rc = VINF_SUCCESS;
1116 }
1117 else
1118 {
1119 rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
1120 szIpAddress[0] = '\0';
1121 cchIpAddress = 0;
1122 }
1123 freeaddrinfo(pgrResults);
1124
1125 /*
1126 * Copy out the result.
1127 */
1128 size_t const cbResult = *pcbResult;
1129 *pcbResult = cchIpAddress + 1;
1130 if (cchIpAddress < cbResult)
1131 memcpy(pszResult, szIpAddress, cchIpAddress + 1);
1132 else
1133 {
1134 RT_BZERO(pszResult, cbResult);
1135 if (RT_SUCCESS(rc))
1136 rc = VERR_BUFFER_OVERFLOW;
1137 }
1138 if (penmAddrType && RT_SUCCESS(rc))
1139 *penmAddrType = enmAddrType;
1140 return rc;
1141
1142# ifdef RT_OS_WINDOWS
1143# undef getaddrinfo
1144# undef freeaddrinfo
1145# endif
1146#endif /* !RT_OS_OS2 */
1147}
1148
1149
1150RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1151{
1152 /*
1153 * Validate input.
1154 */
1155 RTSOCKETINT *pThis = hSocket;
1156 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1157 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1158 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1159 AssertPtr(pvBuffer);
1160#ifdef RT_OS_WINDOWS
1161 AssertReturn(g_pfnrecv, VERR_NET_NOT_UNSUPPORTED);
1162# define recv g_pfnrecv
1163#endif
1164 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1165
1166 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1167 if (RT_FAILURE(rc))
1168 return rc;
1169
1170 /*
1171 * Read loop.
1172 * If pcbRead is NULL we have to fill the entire buffer!
1173 */
1174 size_t cbRead = 0;
1175 size_t cbToRead = cbBuffer;
1176 for (;;)
1177 {
1178 rtSocketErrorReset();
1179#ifdef RTSOCKET_MAX_READ
1180 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
1181#else
1182 size_t cbNow = cbToRead;
1183#endif
1184 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
1185 if (cbBytesRead <= 0)
1186 {
1187 rc = rtSocketError();
1188 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
1189 if (RT_SUCCESS_NP(rc))
1190 {
1191 if (!pcbRead)
1192 rc = VERR_NET_SHUTDOWN;
1193 else
1194 {
1195 *pcbRead = 0;
1196 rc = VINF_SUCCESS;
1197 }
1198 }
1199 break;
1200 }
1201 if (pcbRead)
1202 {
1203 /* return partial data */
1204 *pcbRead = cbBytesRead;
1205 break;
1206 }
1207
1208 /* read more? */
1209 cbRead += cbBytesRead;
1210 if (cbRead == cbBuffer)
1211 break;
1212
1213 /* next */
1214 cbToRead = cbBuffer - cbRead;
1215 }
1216
1217 rtSocketUnlock(pThis);
1218#ifdef RT_OS_WINDOWS
1219# undef recv
1220#endif
1221 return rc;
1222}
1223
1224
1225RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
1226{
1227 /*
1228 * Validate input.
1229 */
1230 RTSOCKETINT *pThis = hSocket;
1231 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1232 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1233 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1234 AssertPtr(pvBuffer);
1235 AssertPtr(pcbRead);
1236#ifdef RT_OS_WINDOWS
1237 AssertReturn(g_pfnrecvfrom, VERR_NET_NOT_UNSUPPORTED);
1238# define recvfrom g_pfnrecvfrom
1239#endif
1240 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1241
1242 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1243 if (RT_FAILURE(rc))
1244 return rc;
1245
1246 /*
1247 * Read data.
1248 */
1249 size_t cbRead = 0;
1250 size_t cbToRead = cbBuffer;
1251 rtSocketErrorReset();
1252 RTSOCKADDRUNION u;
1253#ifdef RTSOCKET_MAX_READ
1254 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
1255 int cbAddr = sizeof(u);
1256#else
1257 size_t cbNow = cbToRead;
1258 socklen_t cbAddr = sizeof(u);
1259#endif
1260 ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
1261 if (cbBytesRead <= 0)
1262 {
1263 rc = rtSocketError();
1264 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
1265 if (RT_SUCCESS_NP(rc))
1266 {
1267 *pcbRead = 0;
1268 rc = VINF_SUCCESS;
1269 }
1270 }
1271 else
1272 {
1273 if (pSrcAddr)
1274 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
1275 *pcbRead = cbBytesRead;
1276 }
1277
1278 rtSocketUnlock(pThis);
1279#ifdef RT_OS_WINDOWS
1280# undef recvfrom
1281#endif
1282 return rc;
1283}
1284
1285
1286RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
1287{
1288 /*
1289 * Validate input.
1290 */
1291 RTSOCKETINT *pThis = hSocket;
1292 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1293 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1294#ifdef RT_OS_WINDOWS
1295 AssertReturn(g_pfnsend, VERR_NET_NOT_UNSUPPORTED);
1296# define send g_pfnsend
1297#endif
1298 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1299
1300 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1301 if (RT_FAILURE(rc))
1302 return rc;
1303
1304 /*
1305 * Try write all at once.
1306 */
1307#ifdef RTSOCKET_MAX_WRITE
1308 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1309#else
1310 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1311#endif
1312 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1313 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1314 rc = VINF_SUCCESS;
1315 else if (cbWritten < 0)
1316 rc = rtSocketError();
1317 else
1318 {
1319 /*
1320 * Unfinished business, write the remainder of the request. Must ignore
1321 * VERR_INTERRUPTED here if we've managed to send something.
1322 */
1323 size_t cbSentSoFar = 0;
1324 for (;;)
1325 {
1326 /* advance */
1327 cbBuffer -= (size_t)cbWritten;
1328 if (!cbBuffer)
1329 break;
1330 cbSentSoFar += (size_t)cbWritten;
1331 pvBuffer = (char const *)pvBuffer + cbWritten;
1332
1333 /* send */
1334#ifdef RTSOCKET_MAX_WRITE
1335 cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1336#else
1337 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1338#endif
1339 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1340 if (cbWritten >= 0)
1341 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
1342 cbWritten, cbBuffer, rtSocketError()));
1343 else
1344 {
1345 rc = rtSocketError();
1346 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
1347 break;
1348 cbWritten = 0;
1349 rc = VINF_SUCCESS;
1350 }
1351 }
1352 }
1353
1354 rtSocketUnlock(pThis);
1355#ifdef RT_OS_WINDOWS
1356# undef send
1357#endif
1358 return rc;
1359}
1360
1361
1362RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1363{
1364 /*
1365 * Validate input.
1366 */
1367 RTSOCKETINT *pThis = hSocket;
1368 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1369 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1370#ifdef RT_OS_WINDOWS
1371 AssertReturn(g_pfnsendto, VERR_NET_NOT_UNSUPPORTED);
1372# define sendto g_pfnsendto
1373#endif
1374
1375 /* no locking since UDP reads may be done concurrently to writes, and
1376 * this is the normal use case of this code. */
1377
1378 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1379 if (RT_FAILURE(rc))
1380 return rc;
1381
1382 /* Figure out destination address. */
1383 struct sockaddr *pSA = NULL;
1384#ifdef RT_OS_WINDOWS
1385 int cbSA = 0;
1386#else
1387 socklen_t cbSA = 0;
1388#endif
1389 RTSOCKADDRUNION u;
1390 if (pAddr)
1391 {
1392 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1393 if (RT_FAILURE(rc))
1394 return rc;
1395 pSA = &u.Addr;
1396 cbSA = sizeof(u);
1397 }
1398
1399 /*
1400 * Must write all at once, otherwise it is a failure.
1401 */
1402#ifdef RT_OS_WINDOWS
1403 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1404#else
1405 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1406#endif
1407 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1408 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1409 rc = VINF_SUCCESS;
1410 else if (cbWritten < 0)
1411 rc = rtSocketError();
1412 else
1413 rc = VERR_TOO_MUCH_DATA;
1414
1415 /// @todo rtSocketUnlock(pThis);
1416#ifdef RT_OS_WINDOWS
1417# undef sendto
1418#endif
1419 return rc;
1420}
1421
1422
1423RTDECL(int) RTSocketWriteToNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1424{
1425 /*
1426 * Validate input.
1427 */
1428 RTSOCKETINT *pThis = hSocket;
1429 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1430 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1431#ifdef RT_OS_WINDOWS
1432 AssertReturn(g_pfnsendto, VERR_NET_NOT_UNSUPPORTED);
1433# define sendto g_pfnsendto
1434#endif
1435
1436 /* no locking since UDP reads may be done concurrently to writes, and
1437 * this is the normal use case of this code. */
1438
1439 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1440 if (RT_FAILURE(rc))
1441 return rc;
1442
1443 /* Figure out destination address. */
1444 struct sockaddr *pSA = NULL;
1445#ifdef RT_OS_WINDOWS
1446 int cbSA = 0;
1447#else
1448 socklen_t cbSA = 0;
1449#endif
1450 RTSOCKADDRUNION u;
1451 if (pAddr)
1452 {
1453 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1454 if (RT_FAILURE(rc))
1455 return rc;
1456 pSA = &u.Addr;
1457 cbSA = sizeof(u);
1458 }
1459
1460 /*
1461 * Must write all at once, otherwise it is a failure.
1462 */
1463#ifdef RT_OS_WINDOWS
1464 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1465#else
1466 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1467#endif
1468 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1469 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1470 rc = VINF_SUCCESS;
1471 else if (cbWritten < 0)
1472 rc = rtSocketError();
1473 else
1474 rc = VERR_TOO_MUCH_DATA;
1475
1476 /// @todo rtSocketUnlock(pThis);
1477#ifdef RT_OS_WINDOWS
1478# undef sendto
1479#endif
1480 return rc;
1481}
1482
1483
1484RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
1485{
1486 /*
1487 * Validate input.
1488 */
1489 RTSOCKETINT *pThis = hSocket;
1490 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1491 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1492 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1493 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1494 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1495
1496 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1497 if (RT_FAILURE(rc))
1498 return rc;
1499
1500 /*
1501 * Construct message descriptor (translate pSgBuf) and send it.
1502 */
1503 rc = VERR_NO_TMP_MEMORY;
1504#ifdef RT_OS_WINDOWS
1505 if (g_pfnWSASend)
1506 {
1507 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
1508 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1509
1510 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
1511 if (paMsg)
1512 {
1513 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1514 {
1515 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
1516 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
1517 }
1518
1519 DWORD dwSent;
1520 int hrc = g_pfnWSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent, MSG_NOSIGNAL, NULL, NULL);
1521 if (!hrc)
1522 rc = VINF_SUCCESS;
1523 /** @todo check for incomplete writes */
1524 else
1525 rc = rtSocketError();
1526
1527 RTMemTmpFree(paMsg);
1528 }
1529 }
1530 else if (g_pfnsend)
1531 {
1532 rc = VINF_SUCCESS;
1533 for (uint32_t iSeg = 0; iSeg < pSgBuf->cSegs; iSeg++)
1534 {
1535 uint8_t const *pbSeg = (uint8_t const *)pSgBuf->paSegs[iSeg].pvSeg;
1536 size_t cbSeg = pSgBuf->paSegs[iSeg].cbSeg;
1537 int cbNow;
1538 ssize_t cbWritten;
1539 for (;;)
1540 {
1541 cbNow = cbSeg >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbSeg;
1542 cbWritten = g_pfnsend(pThis->hNative, (const char *)pbSeg, cbNow, MSG_NOSIGNAL);
1543 if ((size_t)cbWritten >= cbSeg || cbWritten < 0)
1544 break;
1545 pbSeg += cbWritten;
1546 cbSeg -= cbWritten;
1547 }
1548 if (cbWritten < 0)
1549 {
1550 rc = rtSocketError();
1551 break;
1552 }
1553 }
1554 }
1555 else
1556 rc = VERR_NET_NOT_UNSUPPORTED;
1557
1558#else /* !RT_OS_WINDOWS */
1559 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
1560 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1561 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
1562
1563 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
1564 if (paMsg)
1565 {
1566 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1567 {
1568 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
1569 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
1570 }
1571
1572 struct msghdr msgHdr;
1573 RT_ZERO(msgHdr);
1574 msgHdr.msg_iov = paMsg;
1575 msgHdr.msg_iovlen = pSgBuf->cSegs;
1576 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1577 if (RT_LIKELY(cbWritten >= 0))
1578 rc = VINF_SUCCESS;
1579/** @todo check for incomplete writes */
1580 else
1581 rc = rtSocketError();
1582
1583 RTMemTmpFree(paMsg);
1584 }
1585#endif /* !RT_OS_WINDOWS */
1586
1587 rtSocketUnlock(pThis);
1588 return rc;
1589}
1590
1591
1592RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1593{
1594 va_list va;
1595 va_start(va, cSegs);
1596 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1597 va_end(va);
1598 return rc;
1599}
1600
1601
1602RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1603{
1604 /*
1605 * Set up a S/G segment array + buffer on the stack and pass it
1606 * on to RTSocketSgWrite.
1607 */
1608 Assert(cSegs <= 16);
1609 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1610 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1611 for (size_t i = 0; i < cSegs; i++)
1612 {
1613 paSegs[i].pvSeg = va_arg(va, void *);
1614 paSegs[i].cbSeg = va_arg(va, size_t);
1615 }
1616
1617 RTSGBUF SgBuf;
1618 RTSgBufInit(&SgBuf, paSegs, cSegs);
1619 return RTSocketSgWrite(hSocket, &SgBuf);
1620}
1621
1622
1623RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1624{
1625 /*
1626 * Validate input.
1627 */
1628 RTSOCKETINT *pThis = hSocket;
1629 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1630 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1631 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1632 AssertPtr(pvBuffer);
1633 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
1634#ifdef RT_OS_WINDOWS
1635 AssertReturn(g_pfnrecv, VERR_NET_NOT_UNSUPPORTED);
1636#endif
1637 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1638
1639 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1640 if (RT_FAILURE(rc))
1641 return rc;
1642
1643 rtSocketErrorReset();
1644#ifdef RTSOCKET_MAX_READ
1645 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1646#else
1647 size_t cbNow = cbBuffer;
1648#endif
1649
1650#ifdef RT_OS_WINDOWS
1651 int cbRead = g_pfnrecv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1652 if (cbRead >= 0)
1653 {
1654 *pcbRead = cbRead;
1655 rc = VINF_SUCCESS;
1656 }
1657 else
1658 {
1659 rc = rtSocketError();
1660 if (rc == VERR_TRY_AGAIN)
1661 {
1662 *pcbRead = 0;
1663 rc = VINF_TRY_AGAIN;
1664 }
1665 }
1666
1667#else
1668 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
1669 if (cbRead >= 0)
1670 *pcbRead = cbRead;
1671 else if ( errno == EAGAIN
1672# ifdef EWOULDBLOCK
1673# if EWOULDBLOCK != EAGAIN
1674 || errno == EWOULDBLOCK
1675# endif
1676# endif
1677 )
1678 {
1679 *pcbRead = 0;
1680 rc = VINF_TRY_AGAIN;
1681 }
1682 else
1683 rc = rtSocketError();
1684#endif
1685
1686 rtSocketUnlock(pThis);
1687 return rc;
1688}
1689
1690
1691RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1692{
1693 /*
1694 * Validate input.
1695 */
1696 RTSOCKETINT *pThis = hSocket;
1697 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1698 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1699 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1700#ifdef RT_OS_WINDOWS
1701 AssertReturn(g_pfnsend, VERR_NET_NOT_UNSUPPORTED);
1702#endif
1703 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1704
1705 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1706 if (RT_FAILURE(rc))
1707 return rc;
1708
1709 rtSocketErrorReset();
1710#ifdef RT_OS_WINDOWS
1711# ifdef RTSOCKET_MAX_WRITE
1712 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1713# else
1714 size_t cbNow = cbBuffer;
1715# endif
1716 int cbWritten = g_pfnsend(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1717 if (cbWritten >= 0)
1718 {
1719 *pcbWritten = cbWritten;
1720 rc = VINF_SUCCESS;
1721 }
1722 else
1723 {
1724 rc = rtSocketError();
1725 if (rc == VERR_TRY_AGAIN)
1726 {
1727 *pcbWritten = 0;
1728 rc = VINF_TRY_AGAIN;
1729 }
1730 }
1731#else
1732 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1733 if (cbWritten >= 0)
1734 *pcbWritten = cbWritten;
1735 else if ( errno == EAGAIN
1736# ifdef EWOULDBLOCK
1737# if EWOULDBLOCK != EAGAIN
1738 || errno == EWOULDBLOCK
1739# endif
1740# endif
1741 )
1742 {
1743 *pcbWritten = 0;
1744 rc = VINF_TRY_AGAIN;
1745 }
1746 else
1747 rc = rtSocketError();
1748#endif
1749
1750 rtSocketUnlock(pThis);
1751 return rc;
1752}
1753
1754
1755RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1756{
1757 /*
1758 * Validate input.
1759 */
1760 RTSOCKETINT *pThis = hSocket;
1761 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1762 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1763 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1764 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1765 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1766 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1767
1768 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1769 if (RT_FAILURE(rc))
1770 return rc;
1771
1772 unsigned cSegsToSend = 0;
1773 rc = VERR_NO_TMP_MEMORY;
1774#ifdef RT_OS_WINDOWS
1775 if (g_pfnWSASend)
1776 {
1777 LPWSABUF paMsg = NULL;
1778 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1779 if (paMsg)
1780 {
1781 DWORD dwSent = 0;
1782 int hrc = g_pfnWSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent, MSG_NOSIGNAL, NULL, NULL);
1783 if (!hrc)
1784 rc = VINF_SUCCESS;
1785 else
1786 rc = rtSocketError();
1787
1788 *pcbWritten = dwSent;
1789
1790 RTMemTmpFree(paMsg);
1791 }
1792 }
1793 else if (g_pfnsend)
1794 {
1795 size_t cbWrittenTotal = 0;
1796 rc = VINF_SUCCESS;
1797 for (uint32_t iSeg = 0; iSeg < pSgBuf->cSegs; iSeg++)
1798 {
1799 uint8_t const *pbSeg = (uint8_t const *)pSgBuf->paSegs[iSeg].pvSeg;
1800 size_t cbSeg = pSgBuf->paSegs[iSeg].cbSeg;
1801 int cbNow;
1802 ssize_t cbWritten;
1803 for (;;)
1804 {
1805 cbNow = cbSeg >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbSeg;
1806 cbWritten = g_pfnsend(pThis->hNative, (const char *)pbSeg, cbNow, MSG_NOSIGNAL);
1807 if ((size_t)cbWritten >= cbSeg || cbWritten < 0)
1808 break;
1809 cbWrittenTotal += cbWrittenTotal;
1810 pbSeg += cbWritten;
1811 cbSeg -= cbWritten;
1812 }
1813 if (cbWritten < 0)
1814 {
1815 rc = rtSocketError();
1816 break;
1817 }
1818 if (cbWritten != cbNow)
1819 break;
1820 }
1821 *pcbWritten = cbWrittenTotal;
1822 }
1823 else
1824 rc = VERR_NET_NOT_UNSUPPORTED;
1825
1826#else /* !RT_OS_WINDOWS */
1827 struct iovec *paMsg = NULL;
1828
1829 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1830 if (paMsg)
1831 {
1832 struct msghdr msgHdr;
1833 RT_ZERO(msgHdr);
1834 msgHdr.msg_iov = paMsg;
1835 msgHdr.msg_iovlen = cSegsToSend;
1836 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1837 if (RT_LIKELY(cbWritten >= 0))
1838 {
1839 rc = VINF_SUCCESS;
1840 *pcbWritten = cbWritten;
1841 }
1842 else
1843 rc = rtSocketError();
1844
1845 RTMemTmpFree(paMsg);
1846 }
1847#endif /* !RT_OS_WINDOWS */
1848
1849 rtSocketUnlock(pThis);
1850 return rc;
1851}
1852
1853
1854RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1855{
1856 va_list va;
1857 va_start(va, pcbWritten);
1858 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1859 va_end(va);
1860 return rc;
1861}
1862
1863
1864RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1865{
1866 /*
1867 * Set up a S/G segment array + buffer on the stack and pass it
1868 * on to RTSocketSgWrite.
1869 */
1870 Assert(cSegs <= 16);
1871 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1872 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1873 for (size_t i = 0; i < cSegs; i++)
1874 {
1875 paSegs[i].pvSeg = va_arg(va, void *);
1876 paSegs[i].cbSeg = va_arg(va, size_t);
1877 }
1878
1879 RTSGBUF SgBuf;
1880 RTSgBufInit(&SgBuf, paSegs, cSegs);
1881 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1882}
1883
1884
1885RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1886{
1887 /*
1888 * Validate input.
1889 */
1890 RTSOCKETINT *pThis = hSocket;
1891 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1892 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1893 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1894 int const fdMax = (int)pThis->hNative + 1;
1895 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == pThis->hNative, VERR_INTERNAL_ERROR_5);
1896#ifdef RT_OS_WINDOWS
1897 AssertReturn(g_pfnselect, VERR_NET_NOT_UNSUPPORTED);
1898# define select g_pfnselect
1899#endif
1900
1901 /*
1902 * Set up the file descriptor sets and do the select.
1903 */
1904 fd_set fdsetR;
1905 FD_ZERO(&fdsetR);
1906 FD_SET(pThis->hNative, &fdsetR);
1907
1908 fd_set fdsetE = fdsetR;
1909
1910 int rc;
1911 if (cMillies == RT_INDEFINITE_WAIT)
1912 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1913 else
1914 {
1915 struct timeval timeout;
1916 timeout.tv_sec = cMillies / 1000;
1917 timeout.tv_usec = (cMillies % 1000) * 1000;
1918 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1919 }
1920 if (rc > 0)
1921 rc = VINF_SUCCESS;
1922 else if (rc == 0)
1923 rc = VERR_TIMEOUT;
1924 else
1925 rc = rtSocketError();
1926
1927#ifdef RT_OS_WINDOWS
1928# undef select
1929#endif
1930 return rc;
1931}
1932
1933
1934/**
1935 * Internal worker for RTSocketSelectOneEx and rtSocketPollCheck (fallback)
1936 *
1937 * @returns IPRT status code
1938 * @param pThis The socket (valid).
1939 * @param fEvents The events to select for.
1940 * @param pfEvents Where to return the events.
1941 * @param cMillies How long to select for, in milliseconds.
1942 */
1943static int rtSocketSelectOneEx(RTSOCKET pThis, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
1944{
1945 RTSOCKETNATIVE hNative = pThis->hNative;
1946 if (hNative == NIL_RTSOCKETNATIVE)
1947 {
1948 /* Socket is already closed? Possible we raced someone calling rtSocketCloseIt.
1949 Should we return a different status code? */
1950 *pfEvents = RTSOCKET_EVT_ERROR;
1951 return VINF_SUCCESS;
1952 }
1953
1954 int const fdMax = (int)hNative + 1;
1955 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == hNative, VERR_INTERNAL_ERROR_5);
1956#ifdef RT_OS_WINDOWS
1957 AssertReturn(g_pfnselect, VERR_NET_NOT_UNSUPPORTED);
1958 AssertReturn(g_pfn__WSAFDIsSet, VERR_NET_NOT_UNSUPPORTED);
1959# define select g_pfnselect
1960# define __WSAFDIsSet g_pfn__WSAFDIsSet
1961#endif
1962
1963 *pfEvents = 0;
1964
1965 /*
1966 * Set up the file descriptor sets and do the select.
1967 */
1968 fd_set fdsetR;
1969 fd_set fdsetW;
1970 fd_set fdsetE;
1971 FD_ZERO(&fdsetR);
1972 FD_ZERO(&fdsetW);
1973 FD_ZERO(&fdsetE);
1974
1975 if (fEvents & RTSOCKET_EVT_READ)
1976 FD_SET(hNative, &fdsetR);
1977 if (fEvents & RTSOCKET_EVT_WRITE)
1978 FD_SET(hNative, &fdsetW);
1979 if (fEvents & RTSOCKET_EVT_ERROR)
1980 FD_SET(hNative, &fdsetE);
1981
1982 int rc;
1983 if (cMillies == RT_INDEFINITE_WAIT)
1984 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1985 else
1986 {
1987 struct timeval timeout;
1988 timeout.tv_sec = cMillies / 1000;
1989 timeout.tv_usec = (cMillies % 1000) * 1000;
1990 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1991 }
1992 if (rc > 0)
1993 {
1994 if (pThis->hNative == hNative)
1995 {
1996 if (FD_ISSET(hNative, &fdsetR))
1997 *pfEvents |= RTSOCKET_EVT_READ;
1998 if (FD_ISSET(hNative, &fdsetW))
1999 *pfEvents |= RTSOCKET_EVT_WRITE;
2000 if (FD_ISSET(hNative, &fdsetE))
2001 *pfEvents |= RTSOCKET_EVT_ERROR;
2002 rc = VINF_SUCCESS;
2003 }
2004 else
2005 {
2006 /* Socket was closed while we waited (rtSocketCloseIt). Different status code? */
2007 *pfEvents = RTSOCKET_EVT_ERROR;
2008 rc = VINF_SUCCESS;
2009 }
2010 }
2011 else if (rc == 0)
2012 rc = VERR_TIMEOUT;
2013 else
2014 rc = rtSocketError();
2015
2016#ifdef RT_OS_WINDOWS
2017# undef select
2018# undef __WSAFDIsSet
2019#endif
2020 return rc;
2021}
2022
2023
2024RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
2025{
2026 /*
2027 * Validate input.
2028 */
2029 RTSOCKETINT *pThis = hSocket;
2030 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2031 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2032 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
2033 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
2034 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
2035
2036 return rtSocketSelectOneEx(pThis, fEvents, pfEvents, cMillies);
2037}
2038
2039
2040RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
2041{
2042 /*
2043 * Validate input, don't lock it because we might want to interrupt a call
2044 * active on a different thread.
2045 */
2046 RTSOCKETINT *pThis = hSocket;
2047 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2048 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2049 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
2050 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
2051#ifdef RT_OS_WINDOWS
2052 AssertReturn(g_pfnshutdown, VERR_NET_NOT_UNSUPPORTED);
2053# define shutdown g_pfnshutdown
2054#endif
2055
2056 /*
2057 * Do the job.
2058 */
2059 int rc = VINF_SUCCESS;
2060 int fHow;
2061 if (fRead && fWrite)
2062 fHow = SHUT_RDWR;
2063 else if (fRead)
2064 fHow = SHUT_RD;
2065 else
2066 fHow = SHUT_WR;
2067 if (shutdown(pThis->hNative, fHow) == -1)
2068 rc = rtSocketError();
2069
2070#ifdef RT_OS_WINDOWS
2071# undef shutdown
2072#endif
2073 return rc;
2074}
2075
2076
2077RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
2078{
2079 /*
2080 * Validate input.
2081 */
2082 RTSOCKETINT *pThis = hSocket;
2083 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2084 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2085 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
2086#ifdef RT_OS_WINDOWS
2087 AssertReturn(g_pfngetsockname, VERR_NET_NOT_UNSUPPORTED);
2088# define getsockname g_pfngetsockname
2089#endif
2090
2091 /*
2092 * Get the address and convert it.
2093 */
2094 int rc;
2095 RTSOCKADDRUNION u;
2096#ifdef RT_OS_WINDOWS
2097 int cbAddr = sizeof(u);
2098#else
2099 socklen_t cbAddr = sizeof(u);
2100#endif
2101 RT_ZERO(u);
2102 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
2103 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
2104 else
2105 rc = rtSocketError();
2106
2107#ifdef RT_OS_WINDOWS
2108# undef getsockname
2109#endif
2110 return rc;
2111}
2112
2113
2114RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
2115{
2116 /*
2117 * Validate input.
2118 */
2119 RTSOCKETINT *pThis = hSocket;
2120 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2121 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2122 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
2123#ifdef RT_OS_WINDOWS
2124 AssertReturn(g_pfngetpeername, VERR_NET_NOT_UNSUPPORTED);
2125# define getpeername g_pfngetpeername
2126#endif
2127
2128 /*
2129 * Get the address and convert it.
2130 */
2131 int rc;
2132 RTSOCKADDRUNION u;
2133#ifdef RT_OS_WINDOWS
2134 int cbAddr = sizeof(u);
2135#else
2136 socklen_t cbAddr = sizeof(u);
2137#endif
2138 RT_ZERO(u);
2139 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
2140 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
2141 else
2142 rc = rtSocketError();
2143
2144#ifdef RT_OS_WINDOWS
2145# undef getpeername
2146#endif
2147 return rc;
2148}
2149
2150
2151
2152/**
2153 * Wrapper around bind.
2154 *
2155 * @returns IPRT status code.
2156 * @param hSocket The socket handle.
2157 * @param pAddr The address to bind to.
2158 */
2159DECLHIDDEN(int) rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
2160{
2161 RTSOCKADDRUNION u;
2162 int cbAddr;
2163 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
2164 if (RT_SUCCESS(rc))
2165 rc = rtSocketBindRawAddr(hSocket, &u.Addr, cbAddr);
2166 return rc;
2167}
2168
2169
2170/**
2171 * Very thin wrapper around bind.
2172 *
2173 * @returns IPRT status code.
2174 * @param hSocket The socket handle.
2175 * @param pvAddr The address to bind to (struct sockaddr and
2176 * friends).
2177 * @param cbAddr The size of the address.
2178 */
2179DECLHIDDEN(int) rtSocketBindRawAddr(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
2180{
2181 /*
2182 * Validate input.
2183 */
2184 RTSOCKETINT *pThis = hSocket;
2185 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2186 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2187 AssertPtrReturn(pvAddr, VERR_INVALID_POINTER);
2188#ifdef RT_OS_WINDOWS
2189 AssertReturn(g_pfnbind, VERR_NET_NOT_UNSUPPORTED);
2190# define bind g_pfnbind
2191#endif
2192 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2193
2194 int rc;
2195 if (bind(pThis->hNative, (struct sockaddr const *)pvAddr, (int)cbAddr) == 0)
2196 rc = VINF_SUCCESS;
2197 else
2198 rc = rtSocketError();
2199
2200 rtSocketUnlock(pThis);
2201#ifdef RT_OS_WINDOWS
2202# undef bind
2203#endif
2204 return rc;
2205}
2206
2207
2208
2209/**
2210 * Wrapper around listen.
2211 *
2212 * @returns IPRT status code.
2213 * @param hSocket The socket handle.
2214 * @param cMaxPending The max number of pending connections.
2215 */
2216DECLHIDDEN(int) rtSocketListen(RTSOCKET hSocket, int cMaxPending)
2217{
2218 /*
2219 * Validate input.
2220 */
2221 RTSOCKETINT *pThis = hSocket;
2222 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2223 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2224#ifdef RT_OS_WINDOWS
2225 AssertReturn(g_pfnlisten, VERR_NET_NOT_UNSUPPORTED);
2226# define listen g_pfnlisten
2227#endif
2228 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2229
2230 int rc = VINF_SUCCESS;
2231 if (listen(pThis->hNative, cMaxPending) != 0)
2232 rc = rtSocketError();
2233
2234 rtSocketUnlock(pThis);
2235#ifdef RT_OS_WINDOWS
2236# undef listen
2237#endif
2238 return rc;
2239}
2240
2241
2242/**
2243 * Wrapper around accept.
2244 *
2245 * @returns IPRT status code.
2246 * @param hSocket The socket handle.
2247 * @param phClient Where to return the client socket handle on
2248 * success.
2249 * @param pAddr Where to return the client address.
2250 * @param pcbAddr On input this gives the size buffer size of what
2251 * @a pAddr point to. On return this contains the
2252 * size of what's stored at @a pAddr.
2253 */
2254DECLHIDDEN(int) rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
2255{
2256 /*
2257 * Validate input.
2258 * Only lock the socket temporarily while we get the native handle, so that
2259 * we can safely shutdown and destroy the socket from a different thread.
2260 */
2261 RTSOCKETINT *pThis = hSocket;
2262 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2263 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2264#ifdef RT_OS_WINDOWS
2265 AssertReturn(g_pfnaccept, VERR_NET_NOT_UNSUPPORTED);
2266 AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
2267# define accept g_pfnaccept
2268#endif
2269 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2270
2271 /*
2272 * Call accept().
2273 */
2274 rtSocketErrorReset();
2275 int rc = VINF_SUCCESS;
2276#ifdef RT_OS_WINDOWS
2277 int cbAddr = (int)*pcbAddr;
2278#else
2279 socklen_t cbAddr = *pcbAddr;
2280#endif
2281 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
2282 if (hNativeClient != NIL_RTSOCKETNATIVE)
2283 {
2284 *pcbAddr = cbAddr;
2285
2286 /*
2287 * Wrap the client socket.
2288 */
2289 rc = rtSocketCreateForNative(phClient, hNativeClient);
2290 if (RT_FAILURE(rc))
2291 {
2292#ifdef RT_OS_WINDOWS
2293 g_pfnclosesocket(hNativeClient);
2294#else
2295 close(hNativeClient);
2296#endif
2297 }
2298 }
2299 else
2300 rc = rtSocketError();
2301
2302 rtSocketUnlock(pThis);
2303#ifdef RT_OS_WINDOWS
2304# undef accept
2305#endif
2306 return rc;
2307}
2308
2309
2310/**
2311 * Wrapper around connect.
2312 *
2313 * @returns IPRT status code.
2314 * @param hSocket The socket handle.
2315 * @param pAddr The socket address to connect to.
2316 * @param cMillies Number of milliseconds to wait for the connect attempt to complete.
2317 * Use RT_INDEFINITE_WAIT to wait for ever.
2318 * Use RT_TCPCLIENTCONNECT_DEFAULT_WAIT to wait for the default time
2319 * configured on the running system.
2320 */
2321DECLHIDDEN(int) rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr, RTMSINTERVAL cMillies)
2322{
2323 /*
2324 * Validate input.
2325 */
2326 RTSOCKETINT *pThis = hSocket;
2327 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2328 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2329#ifdef RT_OS_WINDOWS
2330 AssertReturn(g_pfnconnect, VERR_NET_NOT_UNSUPPORTED);
2331 AssertReturn(g_pfnselect, VERR_NET_NOT_UNSUPPORTED);
2332 AssertReturn(g_pfngetsockopt, VERR_NET_NOT_UNSUPPORTED);
2333# define connect g_pfnconnect
2334# define select g_pfnselect
2335# define getsockopt g_pfngetsockopt
2336#endif
2337 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2338
2339 RTSOCKADDRUNION u;
2340 int cbAddr;
2341 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
2342 if (RT_SUCCESS(rc))
2343 {
2344 if (cMillies == RT_SOCKETCONNECT_DEFAULT_WAIT)
2345 {
2346 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
2347 rc = rtSocketError();
2348 }
2349 else
2350 {
2351 /*
2352 * Switch the socket to nonblocking mode, initiate the connect
2353 * and wait for the socket to become writable or until the timeout
2354 * expires.
2355 */
2356 rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
2357 if (RT_SUCCESS(rc))
2358 {
2359 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
2360 {
2361 rc = rtSocketError();
2362 if (rc == VERR_TRY_AGAIN || rc == VERR_NET_IN_PROGRESS)
2363 {
2364 int rcSock = 0;
2365 fd_set FdSetWriteable;
2366 struct timeval TvTimeout;
2367
2368 TvTimeout.tv_sec = cMillies / RT_MS_1SEC;
2369 TvTimeout.tv_usec = (cMillies % RT_MS_1SEC) * RT_US_1MS;
2370
2371 FD_ZERO(&FdSetWriteable);
2372 FD_SET(pThis->hNative, &FdSetWriteable);
2373 do
2374 {
2375 rcSock = select(pThis->hNative + 1, NULL, &FdSetWriteable, NULL,
2376 cMillies == RT_INDEFINITE_WAIT || cMillies >= INT_MAX
2377 ? NULL
2378 : &TvTimeout);
2379 if (rcSock > 0)
2380 {
2381 int iSockError = 0;
2382 socklen_t cbSockOpt = sizeof(iSockError);
2383 rcSock = getsockopt(pThis->hNative, SOL_SOCKET, SO_ERROR, (char *)&iSockError, &cbSockOpt);
2384 if (rcSock == 0)
2385 {
2386 if (iSockError == 0)
2387 rc = VINF_SUCCESS;
2388 else
2389 {
2390#ifdef RT_OS_WINDOWS
2391 rc = RTErrConvertFromWin32(iSockError);
2392#else
2393 rc = RTErrConvertFromErrno(iSockError);
2394#endif
2395 }
2396 }
2397 else
2398 rc = rtSocketError();
2399 }
2400 else if (rcSock == 0)
2401 rc = VERR_TIMEOUT;
2402 else
2403 rc = rtSocketError();
2404 } while (rc == VERR_INTERRUPTED);
2405 }
2406 }
2407
2408 rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
2409 }
2410 }
2411 }
2412
2413 rtSocketUnlock(pThis);
2414#ifdef RT_OS_WINDOWS
2415# undef connect
2416# undef select
2417# undef getsockopt
2418#endif
2419 return rc;
2420}
2421
2422
2423/**
2424 * Wrapper around connect, raw address, no timeout.
2425 *
2426 * @returns IPRT status code.
2427 * @param hSocket The socket handle.
2428 * @param pvAddr The raw socket address to connect to.
2429 * @param cbAddr The size of the raw address.
2430 */
2431DECLHIDDEN(int) rtSocketConnectRaw(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
2432{
2433 /*
2434 * Validate input.
2435 */
2436 RTSOCKETINT *pThis = hSocket;
2437 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2438 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2439#ifdef RT_OS_WINDOWS
2440 AssertReturn(g_pfnconnect, VERR_NET_NOT_UNSUPPORTED);
2441# define connect g_pfnconnect
2442#endif
2443 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2444
2445 int rc;
2446 if (connect(pThis->hNative, (const struct sockaddr *)pvAddr, (int)cbAddr) == 0)
2447 rc = VINF_SUCCESS;
2448 else
2449 rc = rtSocketError();
2450
2451 rtSocketUnlock(pThis);
2452#ifdef RT_OS_WINDOWS
2453# undef connect
2454#endif
2455 return rc;
2456}
2457
2458
2459/**
2460 * Wrapper around setsockopt.
2461 *
2462 * @returns IPRT status code.
2463 * @param hSocket The socket handle.
2464 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
2465 * @param iOption The option, e.g. TCP_NODELAY.
2466 * @param pvValue The value buffer.
2467 * @param cbValue The size of the value pointed to by pvValue.
2468 */
2469DECLHIDDEN(int) rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
2470{
2471 /*
2472 * Validate input.
2473 */
2474 RTSOCKETINT *pThis = hSocket;
2475 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2476 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2477#ifdef RT_OS_WINDOWS
2478 AssertReturn(g_pfnsetsockopt, VERR_NET_NOT_UNSUPPORTED);
2479# define setsockopt g_pfnsetsockopt
2480#endif
2481 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2482
2483 int rc = VINF_SUCCESS;
2484 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
2485 rc = rtSocketError();
2486
2487 rtSocketUnlock(pThis);
2488#ifdef RT_OS_WINDOWS
2489# undef setsockopt
2490#endif
2491 return rc;
2492}
2493
2494
2495/**
2496 * Internal RTPollSetAdd helper that returns the handle that should be added to
2497 * the pollset.
2498 *
2499 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
2500 * @param hSocket The socket handle.
2501 * @param fEvents The events we're polling for.
2502 * @param phNative Where to put the primary handle.
2503 */
2504DECLHIDDEN(int) rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
2505{
2506 RTSOCKETINT *pThis = hSocket;
2507 RT_NOREF_PV(fEvents);
2508 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2509 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2510#ifdef RT_OS_WINDOWS
2511 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2512
2513 int rc = VINF_SUCCESS;
2514 if (pThis->hEvent != WSA_INVALID_EVENT)
2515 *phNative = (RTHCINTPTR)pThis->hEvent;
2516 else if (g_pfnWSACreateEvent)
2517 {
2518 pThis->hEvent = g_pfnWSACreateEvent();
2519 *phNative = (RTHCINTPTR)pThis->hEvent;
2520 if (pThis->hEvent == WSA_INVALID_EVENT)
2521 rc = rtSocketError();
2522 }
2523 else
2524 {
2525 AssertCompile(WSA_INVALID_EVENT == (WSAEVENT)NULL);
2526 pThis->hEvent = CreateEventW(NULL, TRUE /*fManualReset*/, FALSE /*fInitialState*/, NULL /*pwszName*/);
2527 *phNative = (RTHCINTPTR)pThis->hEvent;
2528 if (pThis->hEvent == WSA_INVALID_EVENT)
2529 rc = RTErrConvertFromWin32(GetLastError());
2530 }
2531
2532 rtSocketUnlock(pThis);
2533 return rc;
2534
2535#else /* !RT_OS_WINDOWS */
2536 *phNative = (RTHCUINTPTR)pThis->hNative;
2537 return VINF_SUCCESS;
2538#endif /* !RT_OS_WINDOWS */
2539}
2540
2541#ifdef RT_OS_WINDOWS
2542
2543/**
2544 * Fallback poller thread.
2545 *
2546 * @returns VINF_SUCCESS.
2547 * @param hSelf The thread handle.
2548 * @param pvUser Socket instance data.
2549 */
2550static DECLCALLBACK(int) rtSocketPollFallbackThreadProc(RTTHREAD hSelf, void *pvUser)
2551{
2552 RTSOCKETINT *pThis = (RTSOCKETINT *)pvUser;
2553 RT_NOREF(hSelf);
2554# define __WSAFDIsSet g_pfn__WSAFDIsSet
2555
2556 /*
2557 * The execution loop.
2558 */
2559 while (!ASMAtomicReadBool(&pThis->fPollFallbackShutdown))
2560 {
2561 /*
2562 * Do the selecting (with a 15 second timeout because that seems like a good idea).
2563 */
2564 struct fd_set SetRead;
2565 struct fd_set SetWrite;
2566 struct fd_set SetXcpt;
2567
2568 FD_ZERO(&SetRead);
2569 FD_ZERO(&SetWrite);
2570 FD_ZERO(&SetXcpt);
2571
2572 FD_SET(pThis->hPollFallbackNotifyR, &SetRead);
2573 FD_SET(pThis->hPollFallbackNotifyR, &SetXcpt);
2574
2575 bool fActive = ASMAtomicReadBool(&pThis->fPollFallbackActive);
2576 uint32_t fEvents;
2577 if (!fActive)
2578 fEvents = 0;
2579 else
2580 {
2581 fEvents = ASMAtomicReadU32(&pThis->fSubscribedEvts);
2582 if (fEvents & RTPOLL_EVT_READ)
2583 FD_SET(pThis->hNative, &SetRead);
2584 if (fEvents & RTPOLL_EVT_WRITE)
2585 FD_SET(pThis->hNative, &SetWrite);
2586 if (fEvents & RTPOLL_EVT_ERROR)
2587 FD_SET(pThis->hNative, &SetXcpt);
2588 }
2589
2590 struct timeval Timeout;
2591 Timeout.tv_sec = 15;
2592 Timeout.tv_usec = 0;
2593 int rc = g_pfnselect(INT_MAX /*ignored*/, &SetRead, &SetWrite, &SetXcpt, &Timeout);
2594
2595 /* Stop immediately if told to shut down. */
2596 if (ASMAtomicReadBool(&pThis->fPollFallbackShutdown))
2597 break;
2598
2599 /*
2600 * Process the result.
2601 */
2602 if (rc > 0)
2603 {
2604 /* First the socket we're listening on. */
2605 if ( fEvents
2606 && ( FD_ISSET(pThis->hNative, &SetRead)
2607 || FD_ISSET(pThis->hNative, &SetWrite)
2608 || FD_ISSET(pThis->hNative, &SetXcpt)) )
2609 {
2610 ASMAtomicWriteBool(&pThis->fPollFallbackActive, false);
2611 SetEvent(pThis->hEvent);
2612 }
2613
2614 /* Then maintain the notification pipe. (We only read one byte here
2615 because we're overly paranoid wrt socket switching to blocking mode.) */
2616 if (FD_ISSET(pThis->hPollFallbackNotifyR, &SetRead))
2617 {
2618 char chIgnored;
2619 g_pfnrecv(pThis->hPollFallbackNotifyR, &chIgnored, sizeof(chIgnored), MSG_NOSIGNAL);
2620 }
2621 }
2622 else
2623 AssertMsg(rc == 0, ("%Rrc\n", rtSocketError()));
2624 }
2625
2626# undef __WSAFDIsSet
2627 return VINF_SUCCESS;
2628}
2629
2630
2631/**
2632 * Pokes the fallback thread, making sure it gets out of whatever it's stuck in.
2633 *
2634 * @param pThis The socket handle.
2635 */
2636static void rtSocketPokePollFallbackThread(RTSOCKETINT *pThis)
2637{
2638 Assert(pThis->fPollFallback);
2639 if (pThis->hPollFallbackThread != NIL_RTTHREAD)
2640 {
2641 int cbWritten = g_pfnsend(pThis->hPollFallbackNotifyW, "!", 1, MSG_NOSIGNAL);
2642 AssertMsg(cbWritten == 1, ("cbWritten=%d err=%Rrc\n", rtSocketError()));
2643 RT_NOREF_PV(cbWritten);
2644 }
2645}
2646
2647
2648/**
2649 * Called by rtSocketPollStart to make the thread start selecting on the socket.
2650 *
2651 * @returns 0 on success, RTPOLL_EVT_ERROR on failure.
2652 * @param pThis The socket handle.
2653 */
2654static uint32_t rtSocketPollFallbackStart(RTSOCKETINT *pThis)
2655{
2656 /*
2657 * Reset the event and tell the thread to start selecting on the socket.
2658 */
2659 ResetEvent(pThis->hEvent);
2660 ASMAtomicWriteBool(&pThis->fPollFallbackActive, true);
2661
2662 /*
2663 * Wake up the thread the thread.
2664 */
2665 if (pThis->hPollFallbackThread != NIL_RTTHREAD)
2666 rtSocketPokePollFallbackThread(pThis);
2667 else
2668 {
2669 /*
2670 * Not running, need to set it up and start it.
2671 */
2672 AssertLogRelReturn(pThis->hEvent != NULL && pThis->hEvent != INVALID_HANDLE_VALUE, RTPOLL_EVT_ERROR);
2673
2674 /* Create the notification socket pair. */
2675 int rc;
2676 if (pThis->hPollFallbackNotifyR == NIL_RTSOCKETNATIVE)
2677 {
2678 rc = rtSocketCreateNativeTcpPair(&pThis->hPollFallbackNotifyW, &pThis->hPollFallbackNotifyR);
2679 AssertLogRelRCReturn(rc, RTPOLL_EVT_ERROR);
2680
2681 /* Make the read end non-blocking (not fatal). */
2682 u_long fNonBlocking = 1;
2683 rc = g_pfnioctlsocket(pThis->hPollFallbackNotifyR, FIONBIO, &fNonBlocking);
2684 AssertLogRelMsg(rc == 0, ("rc=%#x %Rrc\n", rc, rtSocketError()));
2685 }
2686
2687 /* Finally, start the thread. ASSUME we don't need too much stack. */
2688 rc = RTThreadCreate(&pThis->hPollFallbackThread, rtSocketPollFallbackThreadProc, pThis,
2689 _128K, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "sockpoll");
2690 AssertLogRelRCReturn(rc, RTPOLL_EVT_ERROR);
2691 }
2692 return 0;
2693}
2694
2695
2696/**
2697 * Undos the harm done by WSAEventSelect.
2698 *
2699 * @returns IPRT status code.
2700 * @param pThis The socket handle.
2701 */
2702static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
2703{
2704 int rc = VINF_SUCCESS;
2705 if (pThis->fSubscribedEvts)
2706 {
2707 if (!pThis->fPollFallback)
2708 {
2709 Assert(g_pfnWSAEventSelect && g_pfnioctlsocket);
2710 if (g_pfnWSAEventSelect && g_pfnioctlsocket)
2711 {
2712 if (g_pfnWSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
2713 {
2714 pThis->fSubscribedEvts = 0;
2715
2716 /*
2717 * Switch back to blocking mode if that was the state before the
2718 * operation.
2719 */
2720 if (pThis->fBlocking)
2721 {
2722 u_long fNonBlocking = 0;
2723 int rc2 = g_pfnioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
2724 if (rc2 != 0)
2725 {
2726 rc = rtSocketError();
2727 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
2728 }
2729 }
2730 }
2731 else
2732 {
2733 rc = rtSocketError();
2734 AssertMsgFailed(("%Rrc\n", rc));
2735 }
2736 }
2737 else
2738 {
2739 Assert(pThis->fPollFallback);
2740 rc = VINF_SUCCESS;
2741 }
2742 }
2743 /*
2744 * Just clear the event mask as we never started waiting if we get here.
2745 */
2746 else
2747 ASMAtomicWriteU32(&pThis->fSubscribedEvts, 0);
2748 }
2749 return rc;
2750}
2751
2752
2753/**
2754 * Updates the mask of events we're subscribing to.
2755 *
2756 * @returns IPRT status code.
2757 * @param pThis The socket handle.
2758 * @param fEvents The events we want to subscribe to.
2759 */
2760static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
2761{
2762 if (!pThis->fPollFallback)
2763 {
2764 LONG fNetworkEvents = 0;
2765 if (fEvents & RTPOLL_EVT_READ)
2766 fNetworkEvents |= FD_READ;
2767 if (fEvents & RTPOLL_EVT_WRITE)
2768 fNetworkEvents |= FD_WRITE;
2769 if (fEvents & RTPOLL_EVT_ERROR)
2770 fNetworkEvents |= FD_CLOSE;
2771 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
2772
2773 if (g_pfnWSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
2774 {
2775 pThis->fSubscribedEvts = fEvents;
2776 return VINF_SUCCESS;
2777 }
2778
2779 int rc = rtSocketError();
2780 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
2781 return rc;
2782 }
2783
2784 /*
2785 * Update the events we're waiting for. Caller will poke/start the thread. later
2786 */
2787 ASMAtomicWriteU32(&pThis->fSubscribedEvts, fEvents);
2788 return VINF_SUCCESS;
2789}
2790
2791#endif /* RT_OS_WINDOWS */
2792
2793
2794#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2795
2796/**
2797 * Checks for pending events.
2798 *
2799 * @returns Event mask or 0.
2800 * @param pThis The socket handle.
2801 * @param fEvents The desired events.
2802 */
2803static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
2804{
2805 uint32_t fRetEvents = 0;
2806
2807 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
2808
2809# ifdef RT_OS_WINDOWS
2810 /* Make sure WSAEnumNetworkEvents returns what we want. */
2811 int rc = VINF_SUCCESS;
2812 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
2813 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
2814
2815 if (!pThis->fPollFallback)
2816 {
2817 /* Atomically get pending events and reset the event semaphore. */
2818 Assert(g_pfnWSAEnumNetworkEvents);
2819 WSANETWORKEVENTS NetEvts;
2820 RT_ZERO(NetEvts);
2821 if (g_pfnWSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
2822 {
2823 if ( (NetEvts.lNetworkEvents & FD_READ)
2824 && (fEvents & RTPOLL_EVT_READ)
2825 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
2826 fRetEvents |= RTPOLL_EVT_READ;
2827
2828 if ( (NetEvts.lNetworkEvents & FD_WRITE)
2829 && (fEvents & RTPOLL_EVT_WRITE)
2830 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
2831 fRetEvents |= RTPOLL_EVT_WRITE;
2832
2833 if (fEvents & RTPOLL_EVT_ERROR)
2834 {
2835 if (NetEvts.lNetworkEvents & FD_CLOSE)
2836 fRetEvents |= RTPOLL_EVT_ERROR;
2837 else
2838 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
2839 if ( (NetEvts.lNetworkEvents & (1L << i))
2840 && NetEvts.iErrorCode[i] != 0)
2841 fRetEvents |= RTPOLL_EVT_ERROR;
2842 }
2843 }
2844 else
2845 rc = rtSocketError();
2846 }
2847
2848 /* Fall back on select if we hit an error above or is using fallback polling. */
2849 if (pThis->fPollFallback || RT_FAILURE(rc))
2850 {
2851 rc = rtSocketSelectOneEx(pThis, fEvents & RTPOLL_EVT_ERROR ? fEvents | RTPOLL_EVT_READ : fEvents, &fRetEvents, 0);
2852 if (RT_SUCCESS(rc))
2853 {
2854 /* rtSocketSelectOneEx may return RTPOLL_EVT_READ on disconnect. Use
2855 getpeername to fix this. */
2856 if ((fRetEvents & (RTPOLL_EVT_READ | RTPOLL_EVT_ERROR)) == RTPOLL_EVT_READ)
2857 {
2858# if 0 /* doens't work */
2859 rtSocketErrorReset();
2860 char chIgn;
2861 rc = g_pfnrecv(pThis->hNative, &chIgn, 0, MSG_NOSIGNAL);
2862 rc = rtSocketError();
2863 if (RT_FAILURE(rc))
2864 fRetEvents |= RTPOLL_EVT_ERROR;
2865
2866 rc = g_pfnsend(pThis->hNative, &chIgn, 0, MSG_NOSIGNAL);
2867 rc = rtSocketError();
2868 if (RT_FAILURE(rc))
2869 fRetEvents |= RTPOLL_EVT_ERROR;
2870
2871 RTSOCKADDRUNION u;
2872 int cbAddr = sizeof(u);
2873 if (g_pfngetpeername(pThis->hNative, &u.Addr, &cbAddr) == SOCKET_ERROR)
2874 fRetEvents |= RTPOLL_EVT_ERROR;
2875# endif
2876 /* If no bytes are available, assume error condition. */
2877 u_long cbAvail = 0;
2878 rc = ioctlsocket(pThis->hNative, FIONREAD, &cbAvail);
2879 if (rc == 0 && cbAvail == 0)
2880 fRetEvents |= RTPOLL_EVT_ERROR;
2881 }
2882 fRetEvents &= fEvents | RTPOLL_EVT_ERROR;
2883 }
2884 else if (rc == VERR_TIMEOUT)
2885 fRetEvents = 0;
2886 else
2887 fRetEvents |= RTPOLL_EVT_ERROR;
2888 }
2889
2890# else /* RT_OS_OS2 */
2891 int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
2892 int rc = os2_select(aFds, 1, 1, 1, 0);
2893 if (rc > 0)
2894 {
2895 if (aFds[0] == pThis->hNative)
2896 fRetEvents |= RTPOLL_EVT_READ;
2897 if (aFds[1] == pThis->hNative)
2898 fRetEvents |= RTPOLL_EVT_WRITE;
2899 if (aFds[2] == pThis->hNative)
2900 fRetEvents |= RTPOLL_EVT_ERROR;
2901 fRetEvents &= fEvents;
2902 }
2903# endif /* RT_OS_OS2 */
2904
2905 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
2906 return fRetEvents;
2907}
2908
2909
2910/**
2911 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
2912 * clear, starts whatever actions we've got running during the poll call.
2913 *
2914 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
2915 * Event mask (in @a fEvents) and no actions if the handle is ready
2916 * already.
2917 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
2918 * different poll set.
2919 *
2920 * @param hSocket The socket handle.
2921 * @param hPollSet The poll set handle (for access checks).
2922 * @param fEvents The events we're polling for.
2923 * @param fFinalEntry Set if this is the final entry for this handle
2924 * in this poll set. This can be used for dealing
2925 * with duplicate entries.
2926 * @param fNoWait Set if it's a zero-wait poll call. Clear if
2927 * we'll wait for an event to occur.
2928 *
2929 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
2930 * @c true, we don't currently care about that oddity...
2931 */
2932DECLHIDDEN(uint32_t) rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
2933{
2934 RTSOCKETINT *pThis = hSocket;
2935 AssertPtrReturn(pThis, UINT32_MAX);
2936 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
2937 /** @todo This isn't quite sane. Replace by critsect and open up concurrent
2938 * reads and writes! */
2939 if (rtSocketTryLock(pThis))
2940 pThis->hPollSet = hPollSet;
2941 else
2942 {
2943 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
2944 ASMAtomicIncU32(&pThis->cUsers);
2945 }
2946
2947 /* (rtSocketPollCheck will reset the event object). */
2948# ifdef RT_OS_WINDOWS
2949 uint32_t fRetEvents = pThis->fEventsSaved;
2950 pThis->fEventsSaved = 0; /* Reset */
2951 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
2952
2953 if ( !fRetEvents
2954 && !fNoWait)
2955 {
2956 pThis->fPollEvts |= fEvents;
2957 if ( fFinalEntry
2958 && pThis->fSubscribedEvts != pThis->fPollEvts)
2959 {
2960 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
2961 if (RT_FAILURE(rc))
2962 {
2963 pThis->fPollEvts = 0;
2964 fRetEvents = UINT32_MAX;
2965 }
2966 }
2967 }
2968# else
2969 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2970# endif
2971
2972 if (fRetEvents || fNoWait)
2973 {
2974 if (pThis->cUsers == 1)
2975 {
2976# ifdef RT_OS_WINDOWS
2977 rtSocketPollClearEventAndRestoreBlocking(pThis);
2978# endif
2979 pThis->hPollSet = NIL_RTPOLLSET;
2980 }
2981 ASMAtomicDecU32(&pThis->cUsers);
2982 }
2983# ifdef RT_OS_WINDOWS
2984 /*
2985 * Kick the poller thread on if this is the final entry and we're in
2986 * winsock 1.x fallback mode.
2987 */
2988 else if (pThis->fPollFallback && fFinalEntry)
2989 fRetEvents = rtSocketPollFallbackStart(pThis);
2990# endif
2991
2992 return fRetEvents;
2993}
2994
2995
2996/**
2997 * Called after a WaitForMultipleObjects returned in order to check for pending
2998 * events and stop whatever actions that rtSocketPollStart() initiated.
2999 *
3000 * @returns Event mask or 0.
3001 *
3002 * @param hSocket The socket handle.
3003 * @param fEvents The events we're polling for.
3004 * @param fFinalEntry Set if this is the final entry for this handle
3005 * in this poll set. This can be used for dealing
3006 * with duplicate entries. Only keep in mind that
3007 * this method is called in reverse order, so the
3008 * first call will have this set (when the entire
3009 * set was processed).
3010 * @param fHarvestEvents Set if we should check for pending events.
3011 */
3012DECLHIDDEN(uint32_t) rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
3013{
3014 RTSOCKETINT *pThis = hSocket;
3015 AssertPtrReturn(pThis, 0);
3016 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
3017 Assert(pThis->cUsers > 0);
3018 Assert(pThis->hPollSet != NIL_RTPOLLSET);
3019 RT_NOREF_PV(fFinalEntry);
3020
3021# ifdef RT_OS_WINDOWS
3022 /*
3023 * Deactivate the poll thread if we're in winsock 1.x fallback poll mode.
3024 */
3025 if ( pThis->fPollFallback
3026 && pThis->hPollFallbackThread != NIL_RTTHREAD)
3027 {
3028 ASMAtomicWriteU32(&pThis->fSubscribedEvts, 0);
3029 if (ASMAtomicXchgBool(&pThis->fPollFallbackActive, false))
3030 rtSocketPokePollFallbackThread(pThis);
3031 }
3032# endif
3033
3034 /*
3035 * Harvest events and clear the event mask for the next round of polling.
3036 */
3037 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
3038# ifdef RT_OS_WINDOWS
3039 pThis->fPollEvts = 0;
3040
3041 /*
3042 * Save the write event if required.
3043 * It is only posted once and might get lost if the another source in the
3044 * pollset with a higher priority has pending events.
3045 */
3046 if ( !fHarvestEvents
3047 && fRetEvents)
3048 {
3049 pThis->fEventsSaved = fRetEvents;
3050 fRetEvents = 0;
3051 }
3052# endif
3053
3054 /* Make the socket blocking again and unlock the handle. */
3055 if (pThis->cUsers == 1)
3056 {
3057# ifdef RT_OS_WINDOWS
3058 rtSocketPollClearEventAndRestoreBlocking(pThis);
3059# endif
3060 pThis->hPollSet = NIL_RTPOLLSET;
3061 }
3062 ASMAtomicDecU32(&pThis->cUsers);
3063 return fRetEvents;
3064}
3065
3066#endif /* RT_OS_WINDOWS || RT_OS_OS2 */
3067
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette