VirtualBox

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

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

IPRT/R3: Made the core work on NT 3.51 (still experimental).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 73.5 KB
Line 
1/* $Id: socket.cpp 70195 2017-12-18 13:40:26Z 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#endif /* RT_OS_WINDOWS */
168} RTSOCKETINT;
169
170
171/**
172 * Address union used internally for things like getpeername and getsockname.
173 */
174typedef union RTSOCKADDRUNION
175{
176 struct sockaddr Addr;
177 struct sockaddr_in IPv4;
178#ifdef IPRT_WITH_TCPIP_V6
179 struct sockaddr_in6 IPv6;
180#endif
181} RTSOCKADDRUNION;
182
183
184/**
185 * Get the last error as an iprt status code.
186 *
187 * @returns IPRT status code.
188 */
189DECLINLINE(int) rtSocketError(void)
190{
191#ifdef RT_OS_WINDOWS
192 if (g_pfnWSAGetLastError)
193 return RTErrConvertFromWin32(g_pfnWSAGetLastError());
194 return VERR_NET_IO_ERROR;
195#else
196 return RTErrConvertFromErrno(errno);
197#endif
198}
199
200
201/**
202 * Resets the last error.
203 */
204DECLINLINE(void) rtSocketErrorReset(void)
205{
206#ifdef RT_OS_WINDOWS
207 if (g_pfnWSASetLastError)
208 g_pfnWSASetLastError(0);
209#else
210 errno = 0;
211#endif
212}
213
214
215/**
216 * Get the last resolver error as an iprt status code.
217 *
218 * @returns iprt status code.
219 */
220DECLHIDDEN(int) rtSocketResolverError(void)
221{
222#ifdef RT_OS_WINDOWS
223 if (g_pfnWSAGetLastError)
224 return RTErrConvertFromWin32(g_pfnWSAGetLastError());
225 return VERR_UNRESOLVED_ERROR;
226#else
227 switch (h_errno)
228 {
229 case HOST_NOT_FOUND:
230 return VERR_NET_HOST_NOT_FOUND;
231 case NO_DATA:
232 return VERR_NET_ADDRESS_NOT_AVAILABLE;
233 case NO_RECOVERY:
234 return VERR_IO_GEN_FAILURE;
235 case TRY_AGAIN:
236 return VERR_TRY_AGAIN;
237
238 default:
239 AssertLogRelMsgFailed(("Unhandled error %u\n", h_errno));
240 return VERR_UNRESOLVED_ERROR;
241 }
242#endif
243}
244
245
246/**
247 * Converts from a native socket address to a generic IPRT network address.
248 *
249 * @returns IPRT status code.
250 * @param pSrc The source address.
251 * @param cbSrc The size of the source address.
252 * @param pAddr Where to return the generic IPRT network
253 * address.
254 */
255static int rtSocketNetAddrFromAddr(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
256{
257 /*
258 * Convert the address.
259 */
260 if ( cbSrc == sizeof(struct sockaddr_in)
261 && pSrc->Addr.sa_family == AF_INET)
262 {
263 RT_ZERO(*pAddr);
264 pAddr->enmType = RTNETADDRTYPE_IPV4;
265 pAddr->uPort = RT_N2H_U16(pSrc->IPv4.sin_port);
266 pAddr->uAddr.IPv4.u = pSrc->IPv4.sin_addr.s_addr;
267 }
268#ifdef IPRT_WITH_TCPIP_V6
269 else if ( cbSrc == sizeof(struct sockaddr_in6)
270 && pSrc->Addr.sa_family == AF_INET6)
271 {
272 RT_ZERO(*pAddr);
273 pAddr->enmType = RTNETADDRTYPE_IPV6;
274 pAddr->uPort = RT_N2H_U16(pSrc->IPv6.sin6_port);
275 pAddr->uAddr.IPv6.au32[0] = pSrc->IPv6.sin6_addr.s6_addr32[0];
276 pAddr->uAddr.IPv6.au32[1] = pSrc->IPv6.sin6_addr.s6_addr32[1];
277 pAddr->uAddr.IPv6.au32[2] = pSrc->IPv6.sin6_addr.s6_addr32[2];
278 pAddr->uAddr.IPv6.au32[3] = pSrc->IPv6.sin6_addr.s6_addr32[3];
279 }
280#endif
281 else
282 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
283 return VINF_SUCCESS;
284}
285
286
287/**
288 * Converts from a generic IPRT network address to a native socket address.
289 *
290 * @returns IPRT status code.
291 * @param pAddr Pointer to the generic IPRT network address.
292 * @param pDst The source address.
293 * @param cbDst The size of the source address.
294 * @param pcbAddr Where to store the size of the returned address.
295 * Optional
296 */
297static int rtSocketAddrFromNetAddr(PCRTNETADDR pAddr, RTSOCKADDRUNION *pDst, size_t cbDst, int *pcbAddr)
298{
299 RT_BZERO(pDst, cbDst);
300 if ( pAddr->enmType == RTNETADDRTYPE_IPV4
301 && cbDst >= sizeof(struct sockaddr_in))
302 {
303 pDst->Addr.sa_family = AF_INET;
304 pDst->IPv4.sin_port = RT_H2N_U16(pAddr->uPort);
305 pDst->IPv4.sin_addr.s_addr = pAddr->uAddr.IPv4.u;
306 if (pcbAddr)
307 *pcbAddr = sizeof(pDst->IPv4);
308 }
309#ifdef IPRT_WITH_TCPIP_V6
310 else if ( pAddr->enmType == RTNETADDRTYPE_IPV6
311 && cbDst >= sizeof(struct sockaddr_in6))
312 {
313 pDst->Addr.sa_family = AF_INET6;
314 pDst->IPv6.sin6_port = RT_H2N_U16(pAddr->uPort);
315 pSrc->IPv6.sin6_addr.s6_addr32[0] = pAddr->uAddr.IPv6.au32[0];
316 pSrc->IPv6.sin6_addr.s6_addr32[1] = pAddr->uAddr.IPv6.au32[1];
317 pSrc->IPv6.sin6_addr.s6_addr32[2] = pAddr->uAddr.IPv6.au32[2];
318 pSrc->IPv6.sin6_addr.s6_addr32[3] = pAddr->uAddr.IPv6.au32[3];
319 if (pcbAddr)
320 *pcbAddr = sizeof(pDst->IPv6);
321 }
322#endif
323 else
324 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
325 return VINF_SUCCESS;
326}
327
328
329/**
330 * Tries to lock the socket for exclusive usage by the calling thread.
331 *
332 * Call rtSocketUnlock() to unlock.
333 *
334 * @returns @c true if locked, @c false if not.
335 * @param pThis The socket structure.
336 */
337DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
338{
339 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
340}
341
342
343/**
344 * Unlocks the socket.
345 *
346 * @param pThis The socket structure.
347 */
348DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
349{
350 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
351}
352
353
354/**
355 * The slow path of rtSocketSwitchBlockingMode that does the actual switching.
356 *
357 * @returns IPRT status code.
358 * @param pThis The socket structure.
359 * @param fBlocking The desired mode of operation.
360 * @remarks Do not call directly.
361 */
362static int rtSocketSwitchBlockingModeSlow(RTSOCKETINT *pThis, bool fBlocking)
363{
364#ifdef RT_OS_WINDOWS
365 AssertReturn(g_pfnioctlsocket, VERR_NOT_SUPPORTED);
366 u_long uBlocking = fBlocking ? 0 : 1;
367 if (g_pfnioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
368 return rtSocketError();
369
370#else
371 int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
372 if (fFlags == -1)
373 return rtSocketError();
374
375 if (fBlocking)
376 fFlags &= ~O_NONBLOCK;
377 else
378 fFlags |= O_NONBLOCK;
379 if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
380 return rtSocketError();
381#endif
382
383 pThis->fBlocking = fBlocking;
384 return VINF_SUCCESS;
385}
386
387
388/**
389 * Switches the socket to the desired blocking mode if necessary.
390 *
391 * The socket must be locked.
392 *
393 * @returns IPRT status code.
394 * @param pThis The socket structure.
395 * @param fBlocking The desired mode of operation.
396 */
397DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
398{
399 if (pThis->fBlocking != fBlocking)
400 return rtSocketSwitchBlockingModeSlow(pThis, fBlocking);
401 return VINF_SUCCESS;
402}
403
404
405/**
406 * Creates an IPRT socket handle for a native one.
407 *
408 * @returns IPRT status code.
409 * @param ppSocket Where to return the IPRT socket handle.
410 * @param hNative The native handle.
411 */
412DECLHIDDEN(int) rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
413{
414 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
415 if (!pThis)
416 return VERR_NO_MEMORY;
417 pThis->u32Magic = RTSOCKET_MAGIC;
418 pThis->cUsers = 0;
419 pThis->hNative = hNative;
420 pThis->fClosed = false;
421 pThis->fBlocking = true;
422#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
423 pThis->hPollSet = NIL_RTPOLLSET;
424#endif
425#ifdef RT_OS_WINDOWS
426 pThis->hEvent = WSA_INVALID_EVENT;
427 pThis->fPollEvts = 0;
428 pThis->fSubscribedEvts = 0;
429 pThis->fEventsSaved = 0;
430#endif
431 *ppSocket = pThis;
432 return VINF_SUCCESS;
433}
434
435
436RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
437{
438 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
439#ifndef RT_OS_WINDOWS
440 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
441#endif
442 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
443 return rtSocketCreateForNative(phSocket, uNative);
444}
445
446
447/**
448 * Wrapper around socket().
449 *
450 * @returns IPRT status code.
451 * @param phSocket Where to store the handle to the socket on
452 * success.
453 * @param iDomain The protocol family (PF_XXX).
454 * @param iType The socket type (SOCK_XXX).
455 * @param iProtocol Socket parameter, usually 0.
456 */
457DECLHIDDEN(int) rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
458{
459#ifdef RT_OS_WINDOWS
460 AssertReturn(g_pfnsocket, VERR_NOT_SUPPORTED);
461 AssertReturn(g_pfnclosesocket, VERR_NOT_SUPPORTED);
462#endif
463
464 /*
465 * Create the socket.
466 */
467#ifdef RT_OS_WINDOWS
468 RTSOCKETNATIVE hNative = g_pfnsocket(iDomain, iType, iProtocol);
469#else
470 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
471#endif
472 if (hNative == NIL_RTSOCKETNATIVE)
473 return rtSocketError();
474
475 /*
476 * Wrap it.
477 */
478 int rc = rtSocketCreateForNative(phSocket, hNative);
479 if (RT_FAILURE(rc))
480 {
481#ifdef RT_OS_WINDOWS
482 g_pfnclosesocket(hNative);
483#else
484 close(hNative);
485#endif
486 }
487 return rc;
488}
489
490
491RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
492{
493 RTSOCKETINT *pThis = hSocket;
494 AssertPtrReturn(pThis, UINT32_MAX);
495 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
496 return RTMemPoolRetain(pThis);
497}
498
499
500/**
501 * Worker for RTSocketRelease and RTSocketClose.
502 *
503 * @returns IPRT status code.
504 * @param pThis The socket handle instance data.
505 * @param fDestroy Whether we're reaching ref count zero.
506 */
507static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
508{
509 /*
510 * Invalidate the handle structure on destroy.
511 */
512 if (fDestroy)
513 {
514 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
515 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
516 }
517
518 int rc = VINF_SUCCESS;
519 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
520 {
521 /*
522 * Close the native handle.
523 */
524 RTSOCKETNATIVE hNative = pThis->hNative;
525 if (hNative != NIL_RTSOCKETNATIVE)
526 {
527 pThis->hNative = NIL_RTSOCKETNATIVE;
528
529#ifdef RT_OS_WINDOWS
530 AssertReturn(g_pfnclosesocket, VERR_NOT_SUPPORTED);
531 if (g_pfnclosesocket(hNative))
532#else
533 if (close(hNative))
534#endif
535 {
536 rc = rtSocketError();
537#ifdef RT_OS_WINDOWS
538 AssertMsgFailed(("closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
539#else
540 AssertMsgFailed(("close(%d) -> %Rrc\n", hNative, rc));
541#endif
542 }
543 }
544
545#ifdef RT_OS_WINDOWS
546 /*
547 * Close the event.
548 */
549 WSAEVENT hEvent = pThis->hEvent;
550 if (hEvent == WSA_INVALID_EVENT)
551 {
552 pThis->hEvent = WSA_INVALID_EVENT;
553 Assert(g_pfnWSACloseEvent);
554 if (g_pfnWSACloseEvent)
555 g_pfnWSACloseEvent(hEvent);
556 }
557#endif
558 }
559
560 return rc;
561}
562
563
564RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
565{
566 RTSOCKETINT *pThis = hSocket;
567 if (pThis == NIL_RTSOCKET)
568 return 0;
569 AssertPtrReturn(pThis, UINT32_MAX);
570 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
571
572 /* get the refcount without killing it... */
573 uint32_t cRefs = RTMemPoolRefCount(pThis);
574 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
575 if (cRefs == 1)
576 rtSocketCloseIt(pThis, true);
577
578 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
579}
580
581
582RTDECL(int) RTSocketClose(RTSOCKET hSocket)
583{
584 RTSOCKETINT *pThis = hSocket;
585 if (pThis == NIL_RTSOCKET)
586 return VINF_SUCCESS;
587 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
588 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
589
590 uint32_t cRefs = RTMemPoolRefCount(pThis);
591 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
592
593 int rc = rtSocketCloseIt(pThis, cRefs == 1);
594
595 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
596 return rc;
597}
598
599
600RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
601{
602 RTSOCKETINT *pThis = hSocket;
603 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
604 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
605 return (RTHCUINTPTR)pThis->hNative;
606}
607
608
609RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
610{
611 RTSOCKETINT *pThis = hSocket;
612 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
613 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
614 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
615
616 int rc = VINF_SUCCESS;
617#ifdef RT_OS_WINDOWS
618 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
619 rc = RTErrConvertFromWin32(GetLastError());
620#else
621 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
622 rc = RTErrConvertFromErrno(errno);
623#endif
624
625 return rc;
626}
627
628
629static bool rtSocketIsIPv4Numerical(const char *pszAddress, PRTNETADDRIPV4 pAddr)
630{
631
632 /* Empty address resolves to the INADDR_ANY address (good for bind). */
633 if (!pszAddress || !*pszAddress)
634 {
635 pAddr->u = INADDR_ANY;
636 return true;
637 }
638
639 /* Four quads? */
640 char *psz = (char *)pszAddress;
641 for (int i = 0; i < 4; i++)
642 {
643 uint8_t u8;
644 int rc = RTStrToUInt8Ex(psz, &psz, 0, &u8);
645 if (rc != VINF_SUCCESS && rc != VWRN_TRAILING_CHARS)
646 return false;
647 if (*psz != (i < 3 ? '.' : '\0'))
648 return false;
649 psz++;
650
651 pAddr->au8[i] = u8; /* big endian */
652 }
653
654 return true;
655}
656
657RTDECL(int) RTSocketParseInetAddress(const char *pszAddress, unsigned uPort, PRTNETADDR pAddr)
658{
659 int rc;
660
661 /*
662 * Validate input.
663 */
664 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
665 AssertPtrNullReturn(pszAddress, VERR_INVALID_POINTER);
666
667 /*
668 * Resolve the address. Pretty crude at the moment, but we have to make
669 * sure to not ask the NT 4 gethostbyname about an IPv4 address as it may
670 * give a wrong answer.
671 */
672 /** @todo this only supports IPv4, and IPv6 support needs to be added.
673 * It probably needs to be converted to getaddrinfo(). */
674 RTNETADDRIPV4 IPv4Quad;
675 if (rtSocketIsIPv4Numerical(pszAddress, &IPv4Quad))
676 {
677 Log3(("rtSocketIsIPv4Numerical: %s -> %#x (%RTnaipv4)\n", pszAddress, IPv4Quad.u, IPv4Quad));
678 RT_ZERO(*pAddr);
679 pAddr->enmType = RTNETADDRTYPE_IPV4;
680 pAddr->uPort = uPort;
681 pAddr->uAddr.IPv4 = IPv4Quad;
682 return VINF_SUCCESS;
683 }
684
685#ifdef RT_OS_WINDOWS
686 /* Initialize WinSock and check version before we call gethostbyname. */
687 if ( !g_pfnWSAStartup
688 || !g_pfngethostbyname)
689 return VERR_NOT_SUPPORTED;
690 WORD wVersionRequested = MAKEWORD(1, 1);
691 WSADATA wsaData;
692 RT_ZERO(wsaData);
693 rc = g_pfnWSAStartup(wVersionRequested, &wsaData);
694 if (wsaData.wVersion != wVersionRequested)
695 {
696 AssertMsgFailed(("Wrong winsock version\n"));
697 return VERR_NOT_SUPPORTED;
698 }
699# define gethostbyname g_pfngethostbyname
700#endif
701
702 struct hostent *pHostEnt;
703 pHostEnt = gethostbyname(pszAddress);
704 if (!pHostEnt)
705 {
706 rc = rtSocketResolverError();
707 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
708 return rc;
709 }
710
711 if (pHostEnt->h_addrtype == AF_INET)
712 {
713 RT_ZERO(*pAddr);
714 pAddr->enmType = RTNETADDRTYPE_IPV4;
715 pAddr->uPort = uPort;
716 pAddr->uAddr.IPv4.u = ((struct in_addr *)pHostEnt->h_addr)->s_addr;
717 Log3(("gethostbyname: %s -> %#x (%RTnaipv4)\n", pszAddress, pAddr->uAddr.IPv4.u, pAddr->uAddr.IPv4));
718 }
719 else
720 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
721
722#ifdef RT_OS_WINDOWS
723# undef gethostbyname
724#endif
725 return VINF_SUCCESS;
726}
727
728
729/*
730 * New function to allow both ipv4 and ipv6 addresses to be resolved.
731 * Breaks compatibility with windows before 2000.
732 */
733RTDECL(int) RTSocketQueryAddressStr(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
734{
735 AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
736 AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
737 AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
738 AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);
739
740#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
741 return VERR_NOT_SUPPORTED;
742
743#else
744 int rc;
745 if (*pcbResult < 16)
746 return VERR_NET_ADDRESS_NOT_AVAILABLE;
747
748 /* Setup the hint. */
749 struct addrinfo grHints;
750 RT_ZERO(grHints);
751 grHints.ai_socktype = 0;
752 grHints.ai_flags = 0;
753 grHints.ai_protocol = 0;
754 grHints.ai_family = AF_UNSPEC;
755 if (penmAddrType)
756 {
757 switch (*penmAddrType)
758 {
759 case RTNETADDRTYPE_INVALID:
760 /*grHints.ai_family = AF_UNSPEC;*/
761 break;
762 case RTNETADDRTYPE_IPV4:
763 grHints.ai_family = AF_INET;
764 break;
765 case RTNETADDRTYPE_IPV6:
766 grHints.ai_family = AF_INET6;
767 break;
768 default:
769 AssertFailedReturn(VERR_INVALID_PARAMETER);
770 }
771 }
772
773# ifdef RT_OS_WINDOWS
774 /*
775 * Winsock2 init
776 */
777 if ( !g_pfnWSAStartup
778 || !g_pfngetaddrinfo
779 || !g_pfnfreeaddrinfo)
780 return VERR_NOT_SUPPORTED;
781 /** @todo someone should check if we really need 2, 2 here */
782 WORD wVersionRequested = MAKEWORD(2, 2);
783 WSADATA wsaData;
784 RT_ZERO(wszData);
785 rc = WSAStartup(wVersionRequested, &wsaData);
786 if (wsaData.wVersion != wVersionRequested)
787 {
788 AssertMsgFailed(("Wrong winsock version\n"));
789 return VERR_NOT_SUPPORTED;
790 }
791# define getaddrinfo g_pfngetaddrinfo
792# define freeaddrinfo g_pfnfreeaddrinfo
793# endif
794
795 /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
796 struct addrinfo *pgrResults = NULL;
797 rc = g_pfngetaddrinfo(pszHost, "", &grHints, &pgrResults);
798 if (rc != 0)
799 return VERR_NET_ADDRESS_NOT_AVAILABLE;
800
801 // return data
802 // on multiple matches return only the first one
803
804 if (!pgrResults)
805 return VERR_NET_ADDRESS_NOT_AVAILABLE;
806
807 struct addrinfo const *pgrResult = pgrResults->ai_next;
808 if (!pgrResult)
809 {
810 freeaddrinfo(pgrResults);
811 return VERR_NET_ADDRESS_NOT_AVAILABLE;
812 }
813
814 RTNETADDRTYPE enmAddrType = RTNETADDRTYPE_INVALID;
815 size_t cchIpAddress;
816 char szIpAddress[48];
817 if (pgrResult->ai_family == AF_INET)
818 {
819 struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
820 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
821 "%RTnaipv4", pgrSa->sin_addr.s_addr);
822 Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
823 enmAddrType = RTNETADDRTYPE_IPV4;
824 rc = VINF_SUCCESS;
825 }
826 else if (pgrResult->ai_family == AF_INET6)
827 {
828 struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
829 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
830 "%RTnaipv6", (PRTNETADDRIPV6)&pgrSa6->sin6_addr);
831 enmAddrType = RTNETADDRTYPE_IPV6;
832 rc = VINF_SUCCESS;
833 }
834 else
835 {
836 rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
837 szIpAddress[0] = '\0';
838 cchIpAddress = 0;
839 }
840 freeaddrinfo(pgrResults);
841
842 /*
843 * Copy out the result.
844 */
845 size_t const cbResult = *pcbResult;
846 *pcbResult = cchIpAddress + 1;
847 if (cchIpAddress < cbResult)
848 memcpy(pszResult, szIpAddress, cchIpAddress + 1);
849 else
850 {
851 RT_BZERO(pszResult, cbResult);
852 if (RT_SUCCESS(rc))
853 rc = VERR_BUFFER_OVERFLOW;
854 }
855 if (penmAddrType && RT_SUCCESS(rc))
856 *penmAddrType = enmAddrType;
857 return rc;
858
859# ifdef RT_OS_WINDOWS
860# undef getaddrinfo
861# undef freeaddrinfo
862# endif
863#endif /* !RT_OS_OS2 */
864}
865
866
867RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
868{
869 /*
870 * Validate input.
871 */
872 RTSOCKETINT *pThis = hSocket;
873 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
874 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
875 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
876 AssertPtr(pvBuffer);
877#ifdef RT_OS_WINDOWS
878 AssertReturn(g_pfnrecv, VERR_NOT_SUPPORTED);
879# define recv g_pfnrecv
880#endif
881 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
882
883 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
884 if (RT_FAILURE(rc))
885 return rc;
886
887 /*
888 * Read loop.
889 * If pcbRead is NULL we have to fill the entire buffer!
890 */
891 size_t cbRead = 0;
892 size_t cbToRead = cbBuffer;
893 for (;;)
894 {
895 rtSocketErrorReset();
896#ifdef RTSOCKET_MAX_READ
897 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
898#else
899 size_t cbNow = cbToRead;
900#endif
901 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
902 if (cbBytesRead <= 0)
903 {
904 rc = rtSocketError();
905 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
906 if (RT_SUCCESS_NP(rc))
907 {
908 if (!pcbRead)
909 rc = VERR_NET_SHUTDOWN;
910 else
911 {
912 *pcbRead = 0;
913 rc = VINF_SUCCESS;
914 }
915 }
916 break;
917 }
918 if (pcbRead)
919 {
920 /* return partial data */
921 *pcbRead = cbBytesRead;
922 break;
923 }
924
925 /* read more? */
926 cbRead += cbBytesRead;
927 if (cbRead == cbBuffer)
928 break;
929
930 /* next */
931 cbToRead = cbBuffer - cbRead;
932 }
933
934 rtSocketUnlock(pThis);
935#ifdef RT_OS_WINDOWS
936# undef recv
937#endif
938 return rc;
939}
940
941
942RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
943{
944 /*
945 * Validate input.
946 */
947 RTSOCKETINT *pThis = hSocket;
948 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
949 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
950 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
951 AssertPtr(pvBuffer);
952 AssertPtr(pcbRead);
953#ifdef RT_OS_WINDOWS
954 AssertReturn(g_pfnrecvfrom, VERR_NOT_SUPPORTED);
955# define recvfrom g_pfnrecvfrom
956#endif
957 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
958
959 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
960 if (RT_FAILURE(rc))
961 return rc;
962
963 /*
964 * Read data.
965 */
966 size_t cbRead = 0;
967 size_t cbToRead = cbBuffer;
968 rtSocketErrorReset();
969 RTSOCKADDRUNION u;
970#ifdef RTSOCKET_MAX_READ
971 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
972 int cbAddr = sizeof(u);
973#else
974 size_t cbNow = cbToRead;
975 socklen_t cbAddr = sizeof(u);
976#endif
977 ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
978 if (cbBytesRead <= 0)
979 {
980 rc = rtSocketError();
981 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
982 if (RT_SUCCESS_NP(rc))
983 {
984 *pcbRead = 0;
985 rc = VINF_SUCCESS;
986 }
987 }
988 else
989 {
990 if (pSrcAddr)
991 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
992 *pcbRead = cbBytesRead;
993 }
994
995 rtSocketUnlock(pThis);
996#ifdef RT_OS_WINDOWS
997# undef recvfrom
998#endif
999 return rc;
1000}
1001
1002
1003RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
1004{
1005 /*
1006 * Validate input.
1007 */
1008 RTSOCKETINT *pThis = hSocket;
1009 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1010 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1011#ifdef RT_OS_WINDOWS
1012 AssertReturn(g_pfnsend, VERR_NOT_SUPPORTED);
1013# define send g_pfnsend
1014#endif
1015 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1016
1017 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1018 if (RT_FAILURE(rc))
1019 return rc;
1020
1021 /*
1022 * Try write all at once.
1023 */
1024#ifdef RTSOCKET_MAX_WRITE
1025 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1026#else
1027 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1028#endif
1029 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1030 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1031 rc = VINF_SUCCESS;
1032 else if (cbWritten < 0)
1033 rc = rtSocketError();
1034 else
1035 {
1036 /*
1037 * Unfinished business, write the remainder of the request. Must ignore
1038 * VERR_INTERRUPTED here if we've managed to send something.
1039 */
1040 size_t cbSentSoFar = 0;
1041 for (;;)
1042 {
1043 /* advance */
1044 cbBuffer -= (size_t)cbWritten;
1045 if (!cbBuffer)
1046 break;
1047 cbSentSoFar += (size_t)cbWritten;
1048 pvBuffer = (char const *)pvBuffer + cbWritten;
1049
1050 /* send */
1051#ifdef RTSOCKET_MAX_WRITE
1052 cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1053#else
1054 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1055#endif
1056 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1057 if (cbWritten >= 0)
1058 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
1059 cbWritten, cbBuffer, rtSocketError()));
1060 else
1061 {
1062 rc = rtSocketError();
1063 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
1064 break;
1065 cbWritten = 0;
1066 rc = VINF_SUCCESS;
1067 }
1068 }
1069 }
1070
1071 rtSocketUnlock(pThis);
1072#ifdef RT_OS_WINDOWS
1073# undef send
1074#endif
1075 return rc;
1076}
1077
1078
1079RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1080{
1081 /*
1082 * Validate input.
1083 */
1084 RTSOCKETINT *pThis = hSocket;
1085 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1086 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1087#ifdef RT_OS_WINDOWS
1088 AssertReturn(g_pfnsendto, VERR_NOT_SUPPORTED);
1089# define sendto g_pfnsendto
1090#endif
1091
1092 /* no locking since UDP reads may be done concurrently to writes, and
1093 * this is the normal use case of this code. */
1094
1095 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1096 if (RT_FAILURE(rc))
1097 return rc;
1098
1099 /* Figure out destination address. */
1100 struct sockaddr *pSA = NULL;
1101#ifdef RT_OS_WINDOWS
1102 int cbSA = 0;
1103#else
1104 socklen_t cbSA = 0;
1105#endif
1106 RTSOCKADDRUNION u;
1107 if (pAddr)
1108 {
1109 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1110 if (RT_FAILURE(rc))
1111 return rc;
1112 pSA = &u.Addr;
1113 cbSA = sizeof(u);
1114 }
1115
1116 /*
1117 * Must write all at once, otherwise it is a failure.
1118 */
1119#ifdef RT_OS_WINDOWS
1120 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1121#else
1122 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1123#endif
1124 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1125 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1126 rc = VINF_SUCCESS;
1127 else if (cbWritten < 0)
1128 rc = rtSocketError();
1129 else
1130 rc = VERR_TOO_MUCH_DATA;
1131
1132 ///@todo rtSocketUnlock(pThis);
1133#ifdef RT_OS_WINDOWS
1134# undef sendto
1135#endif
1136 return rc;
1137}
1138
1139
1140RTDECL(int) RTSocketWriteToNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1141{
1142 /*
1143 * Validate input.
1144 */
1145 RTSOCKETINT *pThis = hSocket;
1146 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1147 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1148#ifdef RT_OS_WINDOWS
1149 AssertReturn(g_pfnsendto, VERR_NOT_SUPPORTED);
1150# define sendto g_pfnsendto
1151#endif
1152
1153 /* no locking since UDP reads may be done concurrently to writes, and
1154 * this is the normal use case of this code. */
1155
1156 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1157 if (RT_FAILURE(rc))
1158 return rc;
1159
1160 /* Figure out destination address. */
1161 struct sockaddr *pSA = NULL;
1162#ifdef RT_OS_WINDOWS
1163 int cbSA = 0;
1164#else
1165 socklen_t cbSA = 0;
1166#endif
1167 RTSOCKADDRUNION u;
1168 if (pAddr)
1169 {
1170 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1171 if (RT_FAILURE(rc))
1172 return rc;
1173 pSA = &u.Addr;
1174 cbSA = sizeof(u);
1175 }
1176
1177 /*
1178 * Must write all at once, otherwise it is a failure.
1179 */
1180#ifdef RT_OS_WINDOWS
1181 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1182#else
1183 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1184#endif
1185 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1186 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1187 rc = VINF_SUCCESS;
1188 else if (cbWritten < 0)
1189 rc = rtSocketError();
1190 else
1191 rc = VERR_TOO_MUCH_DATA;
1192
1193 /// @todo rtSocketUnlock(pThis);
1194#ifdef RT_OS_WINDOWS
1195# undef sendto
1196#endif
1197 return rc;
1198}
1199
1200
1201RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
1202{
1203 /*
1204 * Validate input.
1205 */
1206 RTSOCKETINT *pThis = hSocket;
1207 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1208 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1209 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1210 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1211 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1212
1213 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1214 if (RT_FAILURE(rc))
1215 return rc;
1216
1217 /*
1218 * Construct message descriptor (translate pSgBuf) and send it.
1219 */
1220 rc = VERR_NO_TMP_MEMORY;
1221#ifdef RT_OS_WINDOWS
1222 if (g_pfnWSASend)
1223 {
1224 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
1225 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1226
1227 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
1228 if (paMsg)
1229 {
1230 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1231 {
1232 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
1233 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
1234 }
1235
1236 DWORD dwSent;
1237 int hrc = g_pfnWSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent, MSG_NOSIGNAL, NULL, NULL);
1238 if (!hrc)
1239 rc = VINF_SUCCESS;
1240 /** @todo check for incomplete writes */
1241 else
1242 rc = rtSocketError();
1243
1244 RTMemTmpFree(paMsg);
1245 }
1246 }
1247 else if (g_pfnsend)
1248 {
1249 rc = VINF_SUCCESS;
1250 for (uint32_t iSeg = 0; iSeg < pSgBuf->cSegs; iSeg++)
1251 {
1252 uint8_t const *pbSeg = (uint8_t const *)pSgBuf->paSegs[iSeg].pvSeg;
1253 size_t cbSeg = pSgBuf->paSegs[iSeg].cbSeg;
1254 int cbNow;
1255 ssize_t cbWritten;
1256 for (;;)
1257 {
1258 cbNow = cbSeg >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbSeg;
1259 cbWritten = g_pfnsend(pThis->hNative, (const char *)pbSeg, cbNow, MSG_NOSIGNAL);
1260 if ((size_t)cbWritten >= cbSeg || cbWritten < 0)
1261 break;
1262 pbSeg += cbWritten;
1263 cbSeg -= cbWritten;
1264 }
1265 if (cbWritten < 0)
1266 {
1267 rc = rtSocketError();
1268 break;
1269 }
1270 }
1271 }
1272 else
1273 rc = VERR_NOT_SUPPORTED;
1274
1275#else /* !RT_OS_WINDOWS */
1276 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
1277 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1278 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
1279
1280 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
1281 if (paMsg)
1282 {
1283 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1284 {
1285 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
1286 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
1287 }
1288
1289 struct msghdr msgHdr;
1290 RT_ZERO(msgHdr);
1291 msgHdr.msg_iov = paMsg;
1292 msgHdr.msg_iovlen = pSgBuf->cSegs;
1293 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1294 if (RT_LIKELY(cbWritten >= 0))
1295 rc = VINF_SUCCESS;
1296/** @todo check for incomplete writes */
1297 else
1298 rc = rtSocketError();
1299
1300 RTMemTmpFree(paMsg);
1301 }
1302#endif /* !RT_OS_WINDOWS */
1303
1304 rtSocketUnlock(pThis);
1305 return rc;
1306}
1307
1308
1309RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1310{
1311 va_list va;
1312 va_start(va, cSegs);
1313 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1314 va_end(va);
1315 return rc;
1316}
1317
1318
1319RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1320{
1321 /*
1322 * Set up a S/G segment array + buffer on the stack and pass it
1323 * on to RTSocketSgWrite.
1324 */
1325 Assert(cSegs <= 16);
1326 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1327 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1328 for (size_t i = 0; i < cSegs; i++)
1329 {
1330 paSegs[i].pvSeg = va_arg(va, void *);
1331 paSegs[i].cbSeg = va_arg(va, size_t);
1332 }
1333
1334 RTSGBUF SgBuf;
1335 RTSgBufInit(&SgBuf, paSegs, cSegs);
1336 return RTSocketSgWrite(hSocket, &SgBuf);
1337}
1338
1339
1340RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1341{
1342 /*
1343 * Validate input.
1344 */
1345 RTSOCKETINT *pThis = hSocket;
1346 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1347 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1348 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1349 AssertPtr(pvBuffer);
1350 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
1351#ifdef RT_OS_WINDOWS
1352 AssertReturn(g_pfnrecv, VERR_NOT_SUPPORTED);
1353#endif
1354 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1355
1356 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1357 if (RT_FAILURE(rc))
1358 return rc;
1359
1360 rtSocketErrorReset();
1361#ifdef RTSOCKET_MAX_READ
1362 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1363#else
1364 size_t cbNow = cbBuffer;
1365#endif
1366
1367#ifdef RT_OS_WINDOWS
1368 int cbRead = g_pfnrecv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1369 if (cbRead >= 0)
1370 {
1371 *pcbRead = cbRead;
1372 rc = VINF_SUCCESS;
1373 }
1374 else
1375 {
1376 rc = rtSocketError();
1377 if (rc == VERR_TRY_AGAIN)
1378 {
1379 *pcbRead = 0;
1380 rc = VINF_TRY_AGAIN;
1381 }
1382 }
1383
1384#else
1385 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
1386 if (cbRead >= 0)
1387 *pcbRead = cbRead;
1388 else if ( errno == EAGAIN
1389# ifdef EWOULDBLOCK
1390# if EWOULDBLOCK != EAGAIN
1391 || errno == EWOULDBLOCK
1392# endif
1393# endif
1394 )
1395 {
1396 *pcbRead = 0;
1397 rc = VINF_TRY_AGAIN;
1398 }
1399 else
1400 rc = rtSocketError();
1401#endif
1402
1403 rtSocketUnlock(pThis);
1404 return rc;
1405}
1406
1407
1408RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1409{
1410 /*
1411 * Validate input.
1412 */
1413 RTSOCKETINT *pThis = hSocket;
1414 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1415 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1416 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1417#ifdef RT_OS_WINDOWS
1418 AssertReturn(g_pfnsend, VERR_NOT_SUPPORTED);
1419#endif
1420 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1421
1422 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1423 if (RT_FAILURE(rc))
1424 return rc;
1425
1426 rtSocketErrorReset();
1427#ifdef RT_OS_WINDOWS
1428# ifdef RTSOCKET_MAX_WRITE
1429 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1430# else
1431 size_t cbNow = cbBuffer;
1432# endif
1433 int cbWritten = g_pfnsend(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1434 if (cbWritten >= 0)
1435 {
1436 *pcbWritten = cbWritten;
1437 rc = VINF_SUCCESS;
1438 }
1439 else
1440 {
1441 rc = rtSocketError();
1442 if (rc == VERR_TRY_AGAIN)
1443 {
1444 *pcbWritten = 0;
1445 rc = VINF_TRY_AGAIN;
1446 }
1447 }
1448#else
1449 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1450 if (cbWritten >= 0)
1451 *pcbWritten = cbWritten;
1452 else if ( errno == EAGAIN
1453# ifdef EWOULDBLOCK
1454# if EWOULDBLOCK != EAGAIN
1455 || errno == EWOULDBLOCK
1456# endif
1457# endif
1458 )
1459 {
1460 *pcbWritten = 0;
1461 rc = VINF_TRY_AGAIN;
1462 }
1463 else
1464 rc = rtSocketError();
1465#endif
1466
1467 rtSocketUnlock(pThis);
1468 return rc;
1469}
1470
1471
1472RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1473{
1474 /*
1475 * Validate input.
1476 */
1477 RTSOCKETINT *pThis = hSocket;
1478 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1479 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1480 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1481 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1482 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1483 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1484
1485 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1486 if (RT_FAILURE(rc))
1487 return rc;
1488
1489 unsigned cSegsToSend = 0;
1490 rc = VERR_NO_TMP_MEMORY;
1491#ifdef RT_OS_WINDOWS
1492 if (g_pfnWSASend)
1493 {
1494 LPWSABUF paMsg = NULL;
1495 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1496 if (paMsg)
1497 {
1498 DWORD dwSent = 0;
1499 int hrc = g_pfnWSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent, MSG_NOSIGNAL, NULL, NULL);
1500 if (!hrc)
1501 rc = VINF_SUCCESS;
1502 else
1503 rc = rtSocketError();
1504
1505 *pcbWritten = dwSent;
1506
1507 RTMemTmpFree(paMsg);
1508 }
1509 }
1510 else if (g_pfnsend)
1511 {
1512 size_t cbWrittenTotal = 0;
1513 rc = VINF_SUCCESS;
1514 for (uint32_t iSeg = 0; iSeg < pSgBuf->cSegs; iSeg++)
1515 {
1516 uint8_t const *pbSeg = (uint8_t const *)pSgBuf->paSegs[iSeg].pvSeg;
1517 size_t cbSeg = pSgBuf->paSegs[iSeg].cbSeg;
1518 int cbNow;
1519 ssize_t cbWritten;
1520 for (;;)
1521 {
1522 cbNow = cbSeg >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbSeg;
1523 cbWritten = g_pfnsend(pThis->hNative, (const char *)pbSeg, cbNow, MSG_NOSIGNAL);
1524 if ((size_t)cbWritten >= cbSeg || cbWritten < 0)
1525 break;
1526 cbWrittenTotal += cbWrittenTotal;
1527 pbSeg += cbWritten;
1528 cbSeg -= cbWritten;
1529 }
1530 if (cbWritten < 0)
1531 {
1532 rc = rtSocketError();
1533 break;
1534 }
1535 if (cbWritten != cbNow)
1536 break;
1537 }
1538 *pcbWritten = cbWrittenTotal;
1539 }
1540 else
1541 rc = VERR_NOT_SUPPORTED;
1542
1543#else /* !RT_OS_WINDOWS */
1544 struct iovec *paMsg = NULL;
1545
1546 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1547 if (paMsg)
1548 {
1549 struct msghdr msgHdr;
1550 RT_ZERO(msgHdr);
1551 msgHdr.msg_iov = paMsg;
1552 msgHdr.msg_iovlen = cSegsToSend;
1553 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1554 if (RT_LIKELY(cbWritten >= 0))
1555 {
1556 rc = VINF_SUCCESS;
1557 *pcbWritten = cbWritten;
1558 }
1559 else
1560 rc = rtSocketError();
1561
1562 RTMemTmpFree(paMsg);
1563 }
1564#endif /* !RT_OS_WINDOWS */
1565
1566 rtSocketUnlock(pThis);
1567 return rc;
1568}
1569
1570
1571RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1572{
1573 va_list va;
1574 va_start(va, pcbWritten);
1575 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1576 va_end(va);
1577 return rc;
1578}
1579
1580
1581RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1582{
1583 /*
1584 * Set up a S/G segment array + buffer on the stack and pass it
1585 * on to RTSocketSgWrite.
1586 */
1587 Assert(cSegs <= 16);
1588 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1589 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1590 for (size_t i = 0; i < cSegs; i++)
1591 {
1592 paSegs[i].pvSeg = va_arg(va, void *);
1593 paSegs[i].cbSeg = va_arg(va, size_t);
1594 }
1595
1596 RTSGBUF SgBuf;
1597 RTSgBufInit(&SgBuf, paSegs, cSegs);
1598 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1599}
1600
1601
1602RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1603{
1604 /*
1605 * Validate input.
1606 */
1607 RTSOCKETINT *pThis = hSocket;
1608 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1609 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1610 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1611 int const fdMax = (int)pThis->hNative + 1;
1612 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == pThis->hNative, VERR_INTERNAL_ERROR_5);
1613#ifdef RT_OS_WINDOWS
1614 AssertReturn(g_pfnselect, VERR_NOT_SUPPORTED);
1615# define select g_pfnselect
1616#endif
1617
1618 /*
1619 * Set up the file descriptor sets and do the select.
1620 */
1621 fd_set fdsetR;
1622 FD_ZERO(&fdsetR);
1623 FD_SET(pThis->hNative, &fdsetR);
1624
1625 fd_set fdsetE = fdsetR;
1626
1627 int rc;
1628 if (cMillies == RT_INDEFINITE_WAIT)
1629 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1630 else
1631 {
1632 struct timeval timeout;
1633 timeout.tv_sec = cMillies / 1000;
1634 timeout.tv_usec = (cMillies % 1000) * 1000;
1635 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1636 }
1637 if (rc > 0)
1638 rc = VINF_SUCCESS;
1639 else if (rc == 0)
1640 rc = VERR_TIMEOUT;
1641 else
1642 rc = rtSocketError();
1643
1644#ifdef RT_OS_WINDOWS
1645# undef select
1646#endif
1647 return rc;
1648}
1649
1650
1651RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
1652{
1653 /*
1654 * Validate input.
1655 */
1656 RTSOCKETINT *pThis = hSocket;
1657 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1658 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1659 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
1660 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
1661 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1662
1663 RTSOCKETNATIVE hNative = pThis->hNative;
1664 if (hNative == NIL_RTSOCKETNATIVE)
1665 {
1666 /* Socket is already closed? Possible we raced someone calling rtSocketCloseIt.
1667 Should we return a different status code? */
1668 *pfEvents = RTSOCKET_EVT_ERROR;
1669 return VINF_SUCCESS;
1670 }
1671
1672 int const fdMax = (int)hNative + 1;
1673 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == hNative, VERR_INTERNAL_ERROR_5);
1674#ifdef RT_OS_WINDOWS
1675 AssertReturn(g_pfnselect, VERR_NOT_SUPPORTED);
1676 AssertReturn(g_pfn__WSAFDIsSet, VERR_NOT_SUPPORTED);
1677# define select g_pfnselect
1678# define __WSAFDIsSet g_pfn__WSAFDIsSet
1679#endif
1680
1681 *pfEvents = 0;
1682
1683 /*
1684 * Set up the file descriptor sets and do the select.
1685 */
1686 fd_set fdsetR;
1687 fd_set fdsetW;
1688 fd_set fdsetE;
1689 FD_ZERO(&fdsetR);
1690 FD_ZERO(&fdsetW);
1691 FD_ZERO(&fdsetE);
1692
1693 if (fEvents & RTSOCKET_EVT_READ)
1694 FD_SET(hNative, &fdsetR);
1695 if (fEvents & RTSOCKET_EVT_WRITE)
1696 FD_SET(hNative, &fdsetW);
1697 if (fEvents & RTSOCKET_EVT_ERROR)
1698 FD_SET(hNative, &fdsetE);
1699
1700 int rc;
1701 if (cMillies == RT_INDEFINITE_WAIT)
1702 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1703 else
1704 {
1705 struct timeval timeout;
1706 timeout.tv_sec = cMillies / 1000;
1707 timeout.tv_usec = (cMillies % 1000) * 1000;
1708 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1709 }
1710 if (rc > 0)
1711 {
1712 if (pThis->hNative == hNative)
1713 {
1714 if (FD_ISSET(hNative, &fdsetR))
1715 *pfEvents |= RTSOCKET_EVT_READ;
1716 if (FD_ISSET(hNative, &fdsetW))
1717 *pfEvents |= RTSOCKET_EVT_WRITE;
1718 if (FD_ISSET(hNative, &fdsetE))
1719 *pfEvents |= RTSOCKET_EVT_ERROR;
1720 rc = VINF_SUCCESS;
1721 }
1722 else
1723 {
1724 /* Socket was closed while we waited (rtSocketCloseIt). Different status code? */
1725 *pfEvents = RTSOCKET_EVT_ERROR;
1726 rc = VINF_SUCCESS;
1727 }
1728 }
1729 else if (rc == 0)
1730 rc = VERR_TIMEOUT;
1731 else
1732 rc = rtSocketError();
1733
1734#ifdef RT_OS_WINDOWS
1735# undef select
1736# undef __WSAFDIsSet
1737#endif
1738 return rc;
1739}
1740
1741
1742RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1743{
1744 /*
1745 * Validate input, don't lock it because we might want to interrupt a call
1746 * active on a different thread.
1747 */
1748 RTSOCKETINT *pThis = hSocket;
1749 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1750 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1751 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1752 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1753#ifdef RT_OS_WINDOWS
1754 AssertReturn(g_pfnshutdown, VERR_NOT_SUPPORTED);
1755# define shutdown g_pfnshutdown
1756#endif
1757
1758 /*
1759 * Do the job.
1760 */
1761 int rc = VINF_SUCCESS;
1762 int fHow;
1763 if (fRead && fWrite)
1764 fHow = SHUT_RDWR;
1765 else if (fRead)
1766 fHow = SHUT_RD;
1767 else
1768 fHow = SHUT_WR;
1769 if (shutdown(pThis->hNative, fHow) == -1)
1770 rc = rtSocketError();
1771
1772#ifdef RT_OS_WINDOWS
1773# undef shutdown
1774#endif
1775 return rc;
1776}
1777
1778
1779RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1780{
1781 /*
1782 * Validate input.
1783 */
1784 RTSOCKETINT *pThis = hSocket;
1785 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1786 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1787 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1788#ifdef RT_OS_WINDOWS
1789 AssertReturn(g_pfngetsockname, VERR_NOT_SUPPORTED);
1790# define getsockname g_pfngetsockname
1791#endif
1792
1793 /*
1794 * Get the address and convert it.
1795 */
1796 int rc;
1797 RTSOCKADDRUNION u;
1798#ifdef RT_OS_WINDOWS
1799 int cbAddr = sizeof(u);
1800#else
1801 socklen_t cbAddr = sizeof(u);
1802#endif
1803 RT_ZERO(u);
1804 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1805 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1806 else
1807 rc = rtSocketError();
1808
1809#ifdef RT_OS_WINDOWS
1810# undef getsockname
1811#endif
1812 return rc;
1813}
1814
1815
1816RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1817{
1818 /*
1819 * Validate input.
1820 */
1821 RTSOCKETINT *pThis = hSocket;
1822 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1823 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1824 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1825#ifdef RT_OS_WINDOWS
1826 AssertReturn(g_pfngetpeername, VERR_NOT_SUPPORTED);
1827# define getpeername g_pfngetpeername
1828#endif
1829
1830 /*
1831 * Get the address and convert it.
1832 */
1833 int rc;
1834 RTSOCKADDRUNION u;
1835#ifdef RT_OS_WINDOWS
1836 int cbAddr = sizeof(u);
1837#else
1838 socklen_t cbAddr = sizeof(u);
1839#endif
1840 RT_ZERO(u);
1841 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1842 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1843 else
1844 rc = rtSocketError();
1845
1846#ifdef RT_OS_WINDOWS
1847# undef getpeername
1848#endif
1849 return rc;
1850}
1851
1852
1853
1854/**
1855 * Wrapper around bind.
1856 *
1857 * @returns IPRT status code.
1858 * @param hSocket The socket handle.
1859 * @param pAddr The address to bind to.
1860 */
1861DECLHIDDEN(int) rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1862{
1863 RTSOCKADDRUNION u;
1864 int cbAddr;
1865 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1866 if (RT_SUCCESS(rc))
1867 rc = rtSocketBindRawAddr(hSocket, &u.Addr, cbAddr);
1868 return rc;
1869}
1870
1871
1872/**
1873 * Very thin wrapper around bind.
1874 *
1875 * @returns IPRT status code.
1876 * @param hSocket The socket handle.
1877 * @param pvAddr The address to bind to (struct sockaddr and
1878 * friends).
1879 * @param cbAddr The size of the address.
1880 */
1881DECLHIDDEN(int) rtSocketBindRawAddr(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1882{
1883 /*
1884 * Validate input.
1885 */
1886 RTSOCKETINT *pThis = hSocket;
1887 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1888 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1889 AssertPtrReturn(pvAddr, VERR_INVALID_POINTER);
1890#ifdef RT_OS_WINDOWS
1891 AssertReturn(g_pfnbind, VERR_NOT_SUPPORTED);
1892# define bind g_pfnbind
1893#endif
1894 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1895
1896 int rc;
1897 if (bind(pThis->hNative, (struct sockaddr const *)pvAddr, (int)cbAddr) == 0)
1898 rc = VINF_SUCCESS;
1899 else
1900 rc = rtSocketError();
1901
1902 rtSocketUnlock(pThis);
1903#ifdef RT_OS_WINDOWS
1904# undef bind
1905#endif
1906 return rc;
1907}
1908
1909
1910
1911/**
1912 * Wrapper around listen.
1913 *
1914 * @returns IPRT status code.
1915 * @param hSocket The socket handle.
1916 * @param cMaxPending The max number of pending connections.
1917 */
1918DECLHIDDEN(int) rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1919{
1920 /*
1921 * Validate input.
1922 */
1923 RTSOCKETINT *pThis = hSocket;
1924 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1925 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1926#ifdef RT_OS_WINDOWS
1927 AssertReturn(g_pfnlisten, VERR_NOT_SUPPORTED);
1928# define listen g_pfnlisten
1929#endif
1930 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1931
1932 int rc = VINF_SUCCESS;
1933 if (listen(pThis->hNative, cMaxPending) != 0)
1934 rc = rtSocketError();
1935
1936 rtSocketUnlock(pThis);
1937#ifdef RT_OS_WINDOWS
1938# undef listen
1939#endif
1940 return rc;
1941}
1942
1943
1944/**
1945 * Wrapper around accept.
1946 *
1947 * @returns IPRT status code.
1948 * @param hSocket The socket handle.
1949 * @param phClient Where to return the client socket handle on
1950 * success.
1951 * @param pAddr Where to return the client address.
1952 * @param pcbAddr On input this gives the size buffer size of what
1953 * @a pAddr point to. On return this contains the
1954 * size of what's stored at @a pAddr.
1955 */
1956DECLHIDDEN(int) rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1957{
1958 /*
1959 * Validate input.
1960 * Only lock the socket temporarily while we get the native handle, so that
1961 * we can safely shutdown and destroy the socket from a different thread.
1962 */
1963 RTSOCKETINT *pThis = hSocket;
1964 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1965 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1966#ifdef RT_OS_WINDOWS
1967 AssertReturn(g_pfnaccept, VERR_NOT_SUPPORTED);
1968 AssertReturn(g_pfnclosesocket, VERR_NOT_SUPPORTED);
1969# define accept g_pfnaccept
1970#endif
1971 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1972
1973 /*
1974 * Call accept().
1975 */
1976 rtSocketErrorReset();
1977 int rc = VINF_SUCCESS;
1978#ifdef RT_OS_WINDOWS
1979 int cbAddr = (int)*pcbAddr;
1980#else
1981 socklen_t cbAddr = *pcbAddr;
1982#endif
1983 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1984 if (hNativeClient != NIL_RTSOCKETNATIVE)
1985 {
1986 *pcbAddr = cbAddr;
1987
1988 /*
1989 * Wrap the client socket.
1990 */
1991 rc = rtSocketCreateForNative(phClient, hNativeClient);
1992 if (RT_FAILURE(rc))
1993 {
1994#ifdef RT_OS_WINDOWS
1995 g_pfnclosesocket(hNativeClient);
1996#else
1997 close(hNativeClient);
1998#endif
1999 }
2000 }
2001 else
2002 rc = rtSocketError();
2003
2004 rtSocketUnlock(pThis);
2005#ifdef RT_OS_WINDOWS
2006# undef accept
2007#endif
2008 return rc;
2009}
2010
2011
2012/**
2013 * Wrapper around connect.
2014 *
2015 * @returns IPRT status code.
2016 * @param hSocket The socket handle.
2017 * @param pAddr The socket address to connect to.
2018 * @param cMillies Number of milliseconds to wait for the connect attempt to complete.
2019 * Use RT_INDEFINITE_WAIT to wait for ever.
2020 * Use RT_TCPCLIENTCONNECT_DEFAULT_WAIT to wait for the default time
2021 * configured on the running system.
2022 */
2023DECLHIDDEN(int) rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr, RTMSINTERVAL cMillies)
2024{
2025 /*
2026 * Validate input.
2027 */
2028 RTSOCKETINT *pThis = hSocket;
2029 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2030 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2031#ifdef RT_OS_WINDOWS
2032 AssertReturn(g_pfnconnect, VERR_NOT_SUPPORTED);
2033 AssertReturn(g_pfnselect, VERR_NOT_SUPPORTED);
2034 AssertReturn(g_pfngetsockopt, VERR_NOT_SUPPORTED);
2035# define connect g_pfnconnect
2036# define select g_pfnselect
2037# define getsockopt g_pfngetsockopt
2038#endif
2039 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2040
2041 RTSOCKADDRUNION u;
2042 int cbAddr;
2043 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
2044 if (RT_SUCCESS(rc))
2045 {
2046 if (cMillies == RT_SOCKETCONNECT_DEFAULT_WAIT)
2047 {
2048 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
2049 rc = rtSocketError();
2050 }
2051 else
2052 {
2053 /*
2054 * Switch the socket to nonblocking mode, initiate the connect
2055 * and wait for the socket to become writable or until the timeout
2056 * expires.
2057 */
2058 rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
2059 if (RT_SUCCESS(rc))
2060 {
2061 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
2062 {
2063 rc = rtSocketError();
2064 if (rc == VERR_TRY_AGAIN || rc == VERR_NET_IN_PROGRESS)
2065 {
2066 int rcSock = 0;
2067 fd_set FdSetWriteable;
2068 struct timeval TvTimeout;
2069
2070 TvTimeout.tv_sec = cMillies / RT_MS_1SEC;
2071 TvTimeout.tv_usec = (cMillies % RT_MS_1SEC) * RT_US_1MS;
2072
2073 FD_ZERO(&FdSetWriteable);
2074 FD_SET(pThis->hNative, &FdSetWriteable);
2075 do
2076 {
2077 rcSock = select(pThis->hNative + 1, NULL, &FdSetWriteable, NULL,
2078 cMillies == RT_INDEFINITE_WAIT || cMillies >= INT_MAX
2079 ? NULL
2080 : &TvTimeout);
2081 if (rcSock > 0)
2082 {
2083 int iSockError = 0;
2084 socklen_t cbSockOpt = sizeof(iSockError);
2085 rcSock = getsockopt(pThis->hNative, SOL_SOCKET, SO_ERROR, (char *)&iSockError, &cbSockOpt);
2086 if (rcSock == 0)
2087 {
2088 if (iSockError == 0)
2089 rc = VINF_SUCCESS;
2090 else
2091 {
2092#ifdef RT_OS_WINDOWS
2093 rc = RTErrConvertFromWin32(iSockError);
2094#else
2095 rc = RTErrConvertFromErrno(iSockError);
2096#endif
2097 }
2098 }
2099 else
2100 rc = rtSocketError();
2101 }
2102 else if (rcSock == 0)
2103 rc = VERR_TIMEOUT;
2104 else
2105 rc = rtSocketError();
2106 } while (rc == VERR_INTERRUPTED);
2107 }
2108 }
2109
2110 rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
2111 }
2112 }
2113 }
2114
2115 rtSocketUnlock(pThis);
2116#ifdef RT_OS_WINDOWS
2117# undef connect
2118# undef select
2119# undef getsockopt
2120#endif
2121 return rc;
2122}
2123
2124
2125/**
2126 * Wrapper around connect, raw address, no timeout.
2127 *
2128 * @returns IPRT status code.
2129 * @param hSocket The socket handle.
2130 * @param pvAddr The raw socket address to connect to.
2131 * @param cbAddr The size of the raw address.
2132 */
2133DECLHIDDEN(int) rtSocketConnectRaw(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
2134{
2135 /*
2136 * Validate input.
2137 */
2138 RTSOCKETINT *pThis = hSocket;
2139 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2140 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2141#ifdef RT_OS_WINDOWS
2142 AssertReturn(g_pfnconnect, VERR_NOT_SUPPORTED);
2143# define connect g_pfnconnect
2144#endif
2145 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2146
2147 int rc;
2148 if (connect(pThis->hNative, (const struct sockaddr *)pvAddr, (int)cbAddr) == 0)
2149 rc = VINF_SUCCESS;
2150 else
2151 rc = rtSocketError();
2152
2153 rtSocketUnlock(pThis);
2154#ifdef RT_OS_WINDOWS
2155# undef connect
2156#endif
2157 return rc;
2158}
2159
2160
2161/**
2162 * Wrapper around setsockopt.
2163 *
2164 * @returns IPRT status code.
2165 * @param hSocket The socket handle.
2166 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
2167 * @param iOption The option, e.g. TCP_NODELAY.
2168 * @param pvValue The value buffer.
2169 * @param cbValue The size of the value pointed to by pvValue.
2170 */
2171DECLHIDDEN(int) rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
2172{
2173 /*
2174 * Validate input.
2175 */
2176 RTSOCKETINT *pThis = hSocket;
2177 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2178 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2179#ifdef RT_OS_WINDOWS
2180 AssertReturn(g_pfnsetsockopt, VERR_NOT_SUPPORTED);
2181# define setsockopt g_pfnsetsockopt
2182#endif
2183 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2184
2185 int rc = VINF_SUCCESS;
2186 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
2187 rc = rtSocketError();
2188
2189 rtSocketUnlock(pThis);
2190#ifdef RT_OS_WINDOWS
2191# undef setsockopt
2192#endif
2193 return rc;
2194}
2195
2196
2197/**
2198 * Internal RTPollSetAdd helper that returns the handle that should be added to
2199 * the pollset.
2200 *
2201 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
2202 * @param hSocket The socket handle.
2203 * @param fEvents The events we're polling for.
2204 * @param phNative Where to put the primary handle.
2205 */
2206DECLHIDDEN(int) rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
2207{
2208 RTSOCKETINT *pThis = hSocket;
2209 RT_NOREF_PV(fEvents);
2210 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
2211 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
2212#ifdef RT_OS_WINDOWS
2213 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
2214
2215 int rc = VINF_SUCCESS;
2216 if (pThis->hEvent != WSA_INVALID_EVENT)
2217 *phNative = (RTHCINTPTR)pThis->hEvent;
2218 else if (g_pfnWSACreateEvent)
2219 {
2220 pThis->hEvent = g_pfnWSACreateEvent();
2221 *phNative = (RTHCINTPTR)pThis->hEvent;
2222 if (pThis->hEvent == WSA_INVALID_EVENT)
2223 rc = rtSocketError();
2224 }
2225 else
2226 rc = VERR_NOT_SUPPORTED;
2227
2228 rtSocketUnlock(pThis);
2229 return rc;
2230
2231#else /* !RT_OS_WINDOWS */
2232 *phNative = (RTHCUINTPTR)pThis->hNative;
2233 return VINF_SUCCESS;
2234#endif /* !RT_OS_WINDOWS */
2235}
2236
2237#ifdef RT_OS_WINDOWS
2238
2239/**
2240 * Undos the harm done by WSAEventSelect.
2241 *
2242 * @returns IPRT status code.
2243 * @param pThis The socket handle.
2244 */
2245static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
2246{
2247 int rc = VINF_SUCCESS;
2248 if (pThis->fSubscribedEvts)
2249 {
2250 if (g_pfnWSAEventSelect && g_pfnioctlsocket)
2251 {
2252 if (g_pfnWSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
2253 {
2254 pThis->fSubscribedEvts = 0;
2255
2256 /*
2257 * Switch back to blocking mode if that was the state before the
2258 * operation.
2259 */
2260 if (pThis->fBlocking)
2261 {
2262 u_long fNonBlocking = 0;
2263 int rc2 = g_pfnioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
2264 if (rc2 != 0)
2265 {
2266 rc = rtSocketError();
2267 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
2268 }
2269 }
2270 }
2271 else
2272 {
2273 rc = rtSocketError();
2274 AssertMsgFailed(("%Rrc\n", rc));
2275 }
2276 }
2277 else
2278 rc = VERR_NOT_SUPPORTED;
2279 }
2280 return rc;
2281}
2282
2283
2284/**
2285 * Updates the mask of events we're subscribing to.
2286 *
2287 * @returns IPRT status code.
2288 * @param pThis The socket handle.
2289 * @param fEvents The events we want to subscribe to.
2290 */
2291static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
2292{
2293 LONG fNetworkEvents = 0;
2294 if (fEvents & RTPOLL_EVT_READ)
2295 fNetworkEvents |= FD_READ;
2296 if (fEvents & RTPOLL_EVT_WRITE)
2297 fNetworkEvents |= FD_WRITE;
2298 if (fEvents & RTPOLL_EVT_ERROR)
2299 fNetworkEvents |= FD_CLOSE;
2300 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
2301 int rc;
2302 if (g_pfnWSAEventSelect)
2303 {
2304 if (g_pfnWSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
2305 {
2306 pThis->fSubscribedEvts = fEvents;
2307 return VINF_SUCCESS;
2308 }
2309 rc = rtSocketError();
2310 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
2311 }
2312 else
2313 rc = VERR_NOT_SUPPORTED;
2314 return rc;
2315}
2316
2317#endif /* RT_OS_WINDOWS */
2318
2319
2320#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2321
2322/**
2323 * Checks for pending events.
2324 *
2325 * @returns Event mask or 0.
2326 * @param pThis The socket handle.
2327 * @param fEvents The desired events.
2328 */
2329static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
2330{
2331 uint32_t fRetEvents = 0;
2332
2333 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
2334
2335# ifdef RT_OS_WINDOWS
2336 /* Make sure WSAEnumNetworkEvents returns what we want. */
2337 int rc = VINF_SUCCESS;
2338 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
2339 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
2340
2341 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
2342 if (g_pfnWSAEnumNetworkEvents)
2343 {
2344 WSANETWORKEVENTS NetEvts;
2345 RT_ZERO(NetEvts);
2346 if (g_pfnWSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
2347 {
2348 if ( (NetEvts.lNetworkEvents & FD_READ)
2349 && (fEvents & RTPOLL_EVT_READ)
2350 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
2351 fRetEvents |= RTPOLL_EVT_READ;
2352
2353 if ( (NetEvts.lNetworkEvents & FD_WRITE)
2354 && (fEvents & RTPOLL_EVT_WRITE)
2355 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
2356 fRetEvents |= RTPOLL_EVT_WRITE;
2357
2358 if (fEvents & RTPOLL_EVT_ERROR)
2359 {
2360 if (NetEvts.lNetworkEvents & FD_CLOSE)
2361 fRetEvents |= RTPOLL_EVT_ERROR;
2362 else
2363 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
2364 if ( (NetEvts.lNetworkEvents & (1L << i))
2365 && NetEvts.iErrorCode[i] != 0)
2366 fRetEvents |= RTPOLL_EVT_ERROR;
2367 }
2368 }
2369 else
2370 rc = rtSocketError();
2371 }
2372 else if (RT_SUCCESS(rc))
2373 rc = VERR_NOT_SUPPORTED;
2374
2375 /* Fall back on select if we hit an error above. */
2376 if (RT_FAILURE(rc))
2377 {
2378 rc = RTSocketSelectOneEx(pThis, fEvents, &fRetEvents, 0);
2379 if (RT_FAILURE(rc))
2380 fRetEvents = 0;
2381 }
2382
2383#else /* RT_OS_OS2 */
2384 int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
2385 int rc = os2_select(aFds, 1, 1, 1, 0);
2386 if (rc > 0)
2387 {
2388 if (aFds[0] == pThis->hNative)
2389 fRetEvents |= RTPOLL_EVT_READ;
2390 if (aFds[1] == pThis->hNative)
2391 fRetEvents |= RTPOLL_EVT_WRITE;
2392 if (aFds[2] == pThis->hNative)
2393 fRetEvents |= RTPOLL_EVT_ERROR;
2394 fRetEvents &= fEvents;
2395 }
2396#endif /* RT_OS_OS2 */
2397
2398 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
2399 return fRetEvents;
2400}
2401
2402
2403/**
2404 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
2405 * clear, starts whatever actions we've got running during the poll call.
2406 *
2407 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
2408 * Event mask (in @a fEvents) and no actions if the handle is ready
2409 * already.
2410 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
2411 * different poll set.
2412 *
2413 * @param hSocket The socket handle.
2414 * @param hPollSet The poll set handle (for access checks).
2415 * @param fEvents The events we're polling for.
2416 * @param fFinalEntry Set if this is the final entry for this handle
2417 * in this poll set. This can be used for dealing
2418 * with duplicate entries.
2419 * @param fNoWait Set if it's a zero-wait poll call. Clear if
2420 * we'll wait for an event to occur.
2421 *
2422 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
2423 * @c true, we don't currently care about that oddity...
2424 */
2425DECLHIDDEN(uint32_t) rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
2426{
2427 RTSOCKETINT *pThis = hSocket;
2428 AssertPtrReturn(pThis, UINT32_MAX);
2429 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
2430 /** @todo This isn't quite sane. Replace by critsect and open up concurrent
2431 * reads and writes! */
2432 if (rtSocketTryLock(pThis))
2433 pThis->hPollSet = hPollSet;
2434 else
2435 {
2436 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
2437 ASMAtomicIncU32(&pThis->cUsers);
2438 }
2439
2440 /* (rtSocketPollCheck will reset the event object). */
2441# ifdef RT_OS_WINDOWS
2442 uint32_t fRetEvents = pThis->fEventsSaved;
2443 pThis->fEventsSaved = 0; /* Reset */
2444 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
2445
2446 if ( !fRetEvents
2447 && !fNoWait)
2448 {
2449 pThis->fPollEvts |= fEvents;
2450 if ( fFinalEntry
2451 && pThis->fSubscribedEvts != pThis->fPollEvts)
2452 {
2453 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
2454 if (RT_FAILURE(rc))
2455 {
2456 pThis->fPollEvts = 0;
2457 fRetEvents = UINT32_MAX;
2458 }
2459 }
2460 }
2461# else
2462 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2463# endif
2464
2465 if (fRetEvents || fNoWait)
2466 {
2467 if (pThis->cUsers == 1)
2468 {
2469# ifdef RT_OS_WINDOWS
2470 rtSocketPollClearEventAndRestoreBlocking(pThis);
2471# endif
2472 pThis->hPollSet = NIL_RTPOLLSET;
2473 }
2474 ASMAtomicDecU32(&pThis->cUsers);
2475 }
2476
2477 return fRetEvents;
2478}
2479
2480
2481/**
2482 * Called after a WaitForMultipleObjects returned in order to check for pending
2483 * events and stop whatever actions that rtSocketPollStart() initiated.
2484 *
2485 * @returns Event mask or 0.
2486 *
2487 * @param hSocket The socket handle.
2488 * @param fEvents The events we're polling for.
2489 * @param fFinalEntry Set if this is the final entry for this handle
2490 * in this poll set. This can be used for dealing
2491 * with duplicate entries. Only keep in mind that
2492 * this method is called in reverse order, so the
2493 * first call will have this set (when the entire
2494 * set was processed).
2495 * @param fHarvestEvents Set if we should check for pending events.
2496 */
2497DECLHIDDEN(uint32_t) rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2498{
2499 RTSOCKETINT *pThis = hSocket;
2500 AssertPtrReturn(pThis, 0);
2501 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2502 Assert(pThis->cUsers > 0);
2503 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2504 RT_NOREF_PV(fFinalEntry);
2505
2506 /* Harvest events and clear the event mask for the next round of polling. */
2507 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2508# ifdef RT_OS_WINDOWS
2509 pThis->fPollEvts = 0;
2510
2511 /*
2512 * Save the write event if required.
2513 * It is only posted once and might get lost if the another source in the
2514 * pollset with a higher priority has pending events.
2515 */
2516 if ( !fHarvestEvents
2517 && fRetEvents)
2518 {
2519 pThis->fEventsSaved = fRetEvents;
2520 fRetEvents = 0;
2521 }
2522# endif
2523
2524 /* Make the socket blocking again and unlock the handle. */
2525 if (pThis->cUsers == 1)
2526 {
2527# ifdef RT_OS_WINDOWS
2528 rtSocketPollClearEventAndRestoreBlocking(pThis);
2529# endif
2530 pThis->hPollSet = NIL_RTPOLLSET;
2531 }
2532 ASMAtomicDecU32(&pThis->cUsers);
2533 return fRetEvents;
2534}
2535
2536#endif /* RT_OS_WINDOWS || RT_OS_OS2 */
2537
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