VirtualBox

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

Last change on this file since 43205 was 43205, checked in by vboxsync, 13 years ago

cleanup fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 58.2 KB
Line 
1/* $Id: socket.cpp 43205 2012-09-05 13:26:16Z vboxsync $ */
2/** @file
3 * IPRT - Network Sockets.
4 */
5
6/*
7 * Copyright (C) 2006-2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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 <winsock2.h>
33# include <ws2tcpip.h>
34#else /* !RT_OS_WINDOWS */
35# include <errno.h>
36# include <sys/stat.h>
37# include <sys/socket.h>
38# include <netinet/in.h>
39# include <netinet/tcp.h>
40# include <arpa/inet.h>
41# ifdef IPRT_WITH_TCPIP_V6
42# include <netinet6/in6.h>
43# endif
44# include <sys/un.h>
45# include <netdb.h>
46# include <unistd.h>
47# include <fcntl.h>
48# include <sys/uio.h>
49#endif /* !RT_OS_WINDOWS */
50#include <limits.h>
51
52#include "internal/iprt.h"
53#include <iprt/socket.h>
54
55#include <iprt/alloca.h>
56#include <iprt/asm.h>
57#include <iprt/assert.h>
58#include <iprt/ctype.h>
59#include <iprt/err.h>
60#include <iprt/mempool.h>
61#include <iprt/poll.h>
62#include <iprt/string.h>
63#include <iprt/thread.h>
64#include <iprt/time.h>
65#include <iprt/mem.h>
66#include <iprt/sg.h>
67#include <iprt/log.h>
68
69#include "internal/magics.h"
70#include "internal/socket.h"
71#include "internal/string.h"
72
73
74/*******************************************************************************
75* Defined Constants And Macros *
76*******************************************************************************/
77/* non-standard linux stuff (it seems). */
78#ifndef MSG_NOSIGNAL
79# define MSG_NOSIGNAL 0
80#endif
81
82/* Windows has different names for SHUT_XXX. */
83#ifndef SHUT_RDWR
84# ifdef SD_BOTH
85# define SHUT_RDWR SD_BOTH
86# else
87# define SHUT_RDWR 2
88# endif
89#endif
90#ifndef SHUT_WR
91# ifdef SD_SEND
92# define SHUT_WR SD_SEND
93# else
94# define SHUT_WR 1
95# endif
96#endif
97#ifndef SHUT_RD
98# ifdef SD_RECEIVE
99# define SHUT_RD SD_RECEIVE
100# else
101# define SHUT_RD 0
102# endif
103#endif
104
105/* fixup backlevel OSes. */
106#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
107# define socklen_t int
108#endif
109
110/** How many pending connection. */
111#define RTTCP_SERVER_BACKLOG 10
112
113
114/*******************************************************************************
115* Structures and Typedefs *
116*******************************************************************************/
117/**
118 * Socket handle data.
119 *
120 * This is mainly required for implementing RTPollSet on Windows.
121 */
122typedef struct RTSOCKETINT
123{
124 /** Magic number (RTSOCKET_MAGIC). */
125 uint32_t u32Magic;
126 /** Exclusive user count.
127 * This is used to prevent two threads from accessing the handle concurrently.
128 * It can be higher than 1 if this handle is reference multiple times in a
129 * polling set (Windows). */
130 uint32_t volatile cUsers;
131 /** The native socket handle. */
132 RTSOCKETNATIVE hNative;
133 /** Indicates whether the handle has been closed or not. */
134 bool volatile fClosed;
135 /** Indicates whether the socket is operating in blocking or non-blocking mode
136 * currently. */
137 bool fBlocking;
138#ifdef RT_OS_WINDOWS
139 /** The event semaphore we've associated with the socket handle.
140 * This is WSA_INVALID_EVENT if not done. */
141 WSAEVENT hEvent;
142 /** The pollset currently polling this socket. This is NIL if no one is
143 * polling. */
144 RTPOLLSET hPollSet;
145 /** The events we're polling for. */
146 uint32_t fPollEvts;
147 /** The events we're currently subscribing to with WSAEventSelect.
148 * This is ZERO if we're currently not subscribing to anything. */
149 uint32_t fSubscribedEvts;
150 /** Saved events which are only posted once. */
151 uint32_t fEventsSaved;
152#endif /* RT_OS_WINDOWS */
153} RTSOCKETINT;
154
155
156/**
157 * Address union used internally for things like getpeername and getsockname.
158 */
159typedef union RTSOCKADDRUNION
160{
161 struct sockaddr Addr;
162 struct sockaddr_in IPv4;
163#ifdef IPRT_WITH_TCPIP_V6
164 struct sockaddr_in6 IPv6;
165#endif
166} RTSOCKADDRUNION;
167
168
169/**
170 * Get the last error as an iprt status code.
171 *
172 * @returns IPRT status code.
173 */
174DECLINLINE(int) rtSocketError(void)
175{
176#ifdef RT_OS_WINDOWS
177 return RTErrConvertFromWin32(WSAGetLastError());
178#else
179 return RTErrConvertFromErrno(errno);
180#endif
181}
182
183
184/**
185 * Resets the last error.
186 */
187DECLINLINE(void) rtSocketErrorReset(void)
188{
189#ifdef RT_OS_WINDOWS
190 WSASetLastError(0);
191#else
192 errno = 0;
193#endif
194}
195
196
197/**
198 * Get the last resolver error as an iprt status code.
199 *
200 * @returns iprt status code.
201 */
202int rtSocketResolverError(void)
203{
204#ifdef RT_OS_WINDOWS
205 return RTErrConvertFromWin32(WSAGetLastError());
206#else
207 switch (h_errno)
208 {
209 case HOST_NOT_FOUND:
210 return VERR_NET_HOST_NOT_FOUND;
211 case NO_DATA:
212 return VERR_NET_ADDRESS_NOT_AVAILABLE;
213 case NO_RECOVERY:
214 return VERR_IO_GEN_FAILURE;
215 case TRY_AGAIN:
216 return VERR_TRY_AGAIN;
217
218 default:
219 return VERR_UNRESOLVED_ERROR;
220 }
221#endif
222}
223
224
225/**
226 * Converts from a native socket address to a generic IPRT network address.
227 *
228 * @returns IPRT status code.
229 * @param pSrc The source address.
230 * @param cbSrc The size of the source address.
231 * @param pAddr Where to return the generic IPRT network
232 * address.
233 */
234static int rtSocketNetAddrFromAddr(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
235{
236 /*
237 * Convert the address.
238 */
239 if ( cbSrc == sizeof(struct sockaddr_in)
240 && pSrc->Addr.sa_family == AF_INET)
241 {
242 RT_ZERO(*pAddr);
243 pAddr->enmType = RTNETADDRTYPE_IPV4;
244 pAddr->uPort = RT_N2H_U16(pSrc->IPv4.sin_port);
245 pAddr->uAddr.IPv4.u = pSrc->IPv4.sin_addr.s_addr;
246 }
247#ifdef IPRT_WITH_TCPIP_V6
248 else if ( cbSrc == sizeof(struct sockaddr_in6)
249 && pSrc->Addr.sa_family == AF_INET6)
250 {
251 RT_ZERO(*pAddr);
252 pAddr->enmType = RTNETADDRTYPE_IPV6;
253 pAddr->uPort = RT_N2H_U16(pSrc->IPv6.sin6_port);
254 pAddr->uAddr.IPv6.au32[0] = pSrc->IPv6.sin6_addr.s6_addr32[0];
255 pAddr->uAddr.IPv6.au32[1] = pSrc->IPv6.sin6_addr.s6_addr32[1];
256 pAddr->uAddr.IPv6.au32[2] = pSrc->IPv6.sin6_addr.s6_addr32[2];
257 pAddr->uAddr.IPv6.au32[3] = pSrc->IPv6.sin6_addr.s6_addr32[3];
258 }
259#endif
260 else
261 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
262 return VINF_SUCCESS;
263}
264
265
266/**
267 * Converts from a generic IPRT network address to a native socket address.
268 *
269 * @returns IPRT status code.
270 * @param pAddr Pointer to the generic IPRT network address.
271 * @param pDst The source address.
272 * @param cbSrc The size of the source address.
273 * @param pcbAddr Where to store the size of the returned address.
274 * Optional
275 */
276static int rtSocketAddrFromNetAddr(PCRTNETADDR pAddr, RTSOCKADDRUNION *pDst, size_t cbDst, int *pcbAddr)
277{
278 RT_BZERO(pDst, cbDst);
279 if ( pAddr->enmType == RTNETADDRTYPE_IPV4
280 && cbDst >= sizeof(struct sockaddr_in))
281 {
282 pDst->Addr.sa_family = AF_INET;
283 pDst->IPv4.sin_port = RT_H2N_U16(pAddr->uPort);
284 pDst->IPv4.sin_addr.s_addr = pAddr->uAddr.IPv4.u;
285 if (pcbAddr)
286 *pcbAddr = sizeof(pDst->IPv4);
287 }
288#ifdef IPRT_WITH_TCPIP_V6
289 else if ( pAddr->enmType == RTNETADDRTYPE_IPV6
290 && cbDst >= sizeof(struct sockaddr_in6))
291 {
292 pDst->Addr.sa_family = AF_INET6;
293 pDst->IPv6.sin6_port = RT_H2N_U16(pAddr->uPort);
294 pSrc->IPv6.sin6_addr.s6_addr32[0] = pAddr->uAddr.IPv6.au32[0];
295 pSrc->IPv6.sin6_addr.s6_addr32[1] = pAddr->uAddr.IPv6.au32[1];
296 pSrc->IPv6.sin6_addr.s6_addr32[2] = pAddr->uAddr.IPv6.au32[2];
297 pSrc->IPv6.sin6_addr.s6_addr32[3] = pAddr->uAddr.IPv6.au32[3];
298 if (pcbAddr)
299 *pcbAddr = sizeof(pDst->IPv6);
300 }
301#endif
302 else
303 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
304 return VINF_SUCCESS;
305}
306
307
308/**
309 * Tries to lock the socket for exclusive usage by the calling thread.
310 *
311 * Call rtSocketUnlock() to unlock.
312 *
313 * @returns @c true if locked, @c false if not.
314 * @param pThis The socket structure.
315 */
316DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
317{
318 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
319}
320
321
322/**
323 * Unlocks the socket.
324 *
325 * @param pThis The socket structure.
326 */
327DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
328{
329 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
330}
331
332
333/**
334 * The slow path of rtSocketSwitchBlockingMode that does the actual switching.
335 *
336 * @returns IPRT status code.
337 * @param pThis The socket structure.
338 * @param fBlocking The desired mode of operation.
339 * @remarks Do not call directly.
340 */
341static int rtSocketSwitchBlockingModeSlow(RTSOCKETINT *pThis, bool fBlocking)
342{
343#ifdef RT_OS_WINDOWS
344 u_long uBlocking = fBlocking ? 0 : 1;
345 if (ioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
346 return rtSocketError();
347
348#else
349 int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
350 if (fFlags == -1)
351 return rtSocketError();
352
353 if (fBlocking)
354 fFlags &= ~O_NONBLOCK;
355 else
356 fFlags |= O_NONBLOCK;
357 if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
358 return rtSocketError();
359#endif
360
361 pThis->fBlocking = fBlocking;
362 return VINF_SUCCESS;
363}
364
365
366/**
367 * Switches the socket to the desired blocking mode if necessary.
368 *
369 * The socket must be locked.
370 *
371 * @returns IPRT status code.
372 * @param pThis The socket structure.
373 * @param fBlocking The desired mode of operation.
374 */
375DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
376{
377 if (pThis->fBlocking != fBlocking)
378 return rtSocketSwitchBlockingModeSlow(pThis, fBlocking);
379 return VINF_SUCCESS;
380}
381
382
383/**
384 * Creates an IPRT socket handle for a native one.
385 *
386 * @returns IPRT status code.
387 * @param ppSocket Where to return the IPRT socket handle.
388 * @param hNative The native handle.
389 */
390int rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
391{
392 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
393 if (!pThis)
394 return VERR_NO_MEMORY;
395 pThis->u32Magic = RTSOCKET_MAGIC;
396 pThis->cUsers = 0;
397 pThis->hNative = hNative;
398 pThis->fClosed = false;
399 pThis->fBlocking = true;
400#ifdef RT_OS_WINDOWS
401 pThis->hEvent = WSA_INVALID_EVENT;
402 pThis->hPollSet = NIL_RTPOLLSET;
403 pThis->fPollEvts = 0;
404 pThis->fSubscribedEvts = 0;
405#endif
406 *ppSocket = pThis;
407 return VINF_SUCCESS;
408}
409
410
411RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
412{
413 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
414#ifndef RT_OS_WINDOWS
415 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
416#endif
417 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
418 return rtSocketCreateForNative(phSocket, uNative);
419}
420
421
422/**
423 * Wrapper around socket().
424 *
425 * @returns IPRT status code.
426 * @param phSocket Where to store the handle to the socket on
427 * success.
428 * @param iDomain The protocol family (PF_XXX).
429 * @param iType The socket type (SOCK_XXX).
430 * @param iProtocol Socket parameter, usually 0.
431 */
432int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
433{
434 /*
435 * Create the socket.
436 */
437 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
438 if (hNative == NIL_RTSOCKETNATIVE)
439 return rtSocketError();
440
441 /*
442 * Wrap it.
443 */
444 int rc = rtSocketCreateForNative(phSocket, hNative);
445 if (RT_FAILURE(rc))
446 {
447#ifdef RT_OS_WINDOWS
448 closesocket(hNative);
449#else
450 close(hNative);
451#endif
452 }
453 return rc;
454}
455
456
457RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
458{
459 RTSOCKETINT *pThis = hSocket;
460 AssertPtrReturn(pThis, UINT32_MAX);
461 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
462 return RTMemPoolRetain(pThis);
463}
464
465
466/**
467 * Worker for RTSocketRelease and RTSocketClose.
468 *
469 * @returns IPRT status code.
470 * @param pThis The socket handle instance data.
471 * @param fDestroy Whether we're reaching ref count zero.
472 */
473static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
474{
475 /*
476 * Invalidate the handle structure on destroy.
477 */
478 if (fDestroy)
479 {
480 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
481 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
482 }
483
484 int rc = VINF_SUCCESS;
485 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
486 {
487 /*
488 * Close the native handle.
489 */
490 RTSOCKETNATIVE hNative = pThis->hNative;
491 if (hNative != NIL_RTSOCKETNATIVE)
492 {
493 pThis->hNative = NIL_RTSOCKETNATIVE;
494
495#ifdef RT_OS_WINDOWS
496 if (closesocket(hNative))
497#else
498 if (close(hNative))
499#endif
500 {
501 rc = rtSocketError();
502#ifdef RT_OS_WINDOWS
503 AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
504#else
505 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", hNative, rc));
506#endif
507 }
508 }
509
510#ifdef RT_OS_WINDOWS
511 /*
512 * Close the event.
513 */
514 WSAEVENT hEvent = pThis->hEvent;
515 if (hEvent == WSA_INVALID_EVENT)
516 {
517 pThis->hEvent = WSA_INVALID_EVENT;
518 WSACloseEvent(hEvent);
519 }
520#endif
521 }
522
523 return rc;
524}
525
526
527RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
528{
529 RTSOCKETINT *pThis = hSocket;
530 if (pThis == NIL_RTSOCKET)
531 return 0;
532 AssertPtrReturn(pThis, UINT32_MAX);
533 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
534
535 /* get the refcount without killing it... */
536 uint32_t cRefs = RTMemPoolRefCount(pThis);
537 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
538 if (cRefs == 1)
539 rtSocketCloseIt(pThis, true);
540
541 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
542}
543
544
545RTDECL(int) RTSocketClose(RTSOCKET hSocket)
546{
547 RTSOCKETINT *pThis = hSocket;
548 if (pThis == NIL_RTSOCKET)
549 return VINF_SUCCESS;
550 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
551 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
552
553 uint32_t cRefs = RTMemPoolRefCount(pThis);
554 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
555
556 int rc = rtSocketCloseIt(pThis, cRefs == 1);
557
558 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
559 return rc;
560}
561
562
563RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
564{
565 RTSOCKETINT *pThis = hSocket;
566 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
567 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
568 return (RTHCUINTPTR)pThis->hNative;
569}
570
571
572RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
573{
574 RTSOCKETINT *pThis = hSocket;
575 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
576 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
577 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
578
579 int rc = VINF_SUCCESS;
580#ifdef RT_OS_WINDOWS
581 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
582 rc = RTErrConvertFromWin32(GetLastError());
583#else
584 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
585 rc = RTErrConvertFromErrno(errno);
586#endif
587
588 return rc;
589}
590
591
592static bool rtSocketIsIPv4Numerical(const char *pszAddress, PRTNETADDRIPV4 pAddr)
593{
594
595 /* Empty address resolves to the INADDR_ANY address (good for bind). */
596 if (!pszAddress || !*pszAddress)
597 {
598 pAddr->u = INADDR_ANY;
599 return true;
600 }
601
602 /* Four quads? */
603 char *psz = (char *)pszAddress;
604 for (int i = 0; i < 4; i++)
605 {
606 uint8_t u8;
607 int rc = RTStrToUInt8Ex(psz, &psz, 0, &u8);
608 if (rc != VINF_SUCCESS && rc != VWRN_TRAILING_CHARS)
609 return false;
610 if (*psz != (i < 3 ? '.' : '\0'))
611 return false;
612 psz++;
613
614 pAddr->au8[i] = u8; /* big endian */
615 }
616
617 return true;
618}
619
620RTDECL(int) RTSocketParseInetAddress(const char *pszAddress, unsigned uPort, PRTNETADDR pAddr)
621{
622 int rc;
623
624 /*
625 * Validate input.
626 */
627 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
628 AssertPtrNullReturn(pszAddress, VERR_INVALID_POINTER);
629
630#ifdef RT_OS_WINDOWS
631 /*
632 * Initialize WinSock and check version.
633 */
634 WORD wVersionRequested = MAKEWORD(1, 1);
635 WSADATA wsaData;
636 rc = WSAStartup(wVersionRequested, &wsaData);
637 if (wsaData.wVersion != wVersionRequested)
638 {
639 AssertMsgFailed(("Wrong winsock version\n"));
640 return VERR_NOT_SUPPORTED;
641 }
642#endif
643
644 /*
645 * Resolve the address. Pretty crude at the moment, but we have to make
646 * sure to not ask the NT 4 gethostbyname about an IPv4 address as it may
647 * give a wrong answer.
648 */
649 /** @todo this only supports IPv4, and IPv6 support needs to be added.
650 * It probably needs to be converted to getaddrinfo(). */
651 RTNETADDRIPV4 IPv4Quad;
652 if (rtSocketIsIPv4Numerical(pszAddress, &IPv4Quad))
653 {
654 Log3(("rtSocketIsIPv4Numerical: %#x (%RTnaipv4)\n", pszAddress, IPv4Quad.u, IPv4Quad));
655 RT_ZERO(*pAddr);
656 pAddr->enmType = RTNETADDRTYPE_IPV4;
657 pAddr->uPort = uPort;
658 pAddr->uAddr.IPv4 = IPv4Quad;
659 return VINF_SUCCESS;
660 }
661
662 struct hostent *pHostEnt;
663 pHostEnt = gethostbyname(pszAddress);
664 if (!pHostEnt)
665 {
666 rc = rtSocketResolverError();
667 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
668 return rc;
669 }
670
671 if (pHostEnt->h_addrtype == AF_INET)
672 {
673 RT_ZERO(*pAddr);
674 pAddr->enmType = RTNETADDRTYPE_IPV4;
675 pAddr->uPort = uPort;
676 pAddr->uAddr.IPv4.u = ((struct in_addr *)pHostEnt->h_addr)->s_addr;
677 Log3(("gethostbyname: %s -> %#x (%RTnaipv4)\n", pszAddress, pAddr->uAddr.IPv4.u, pAddr->uAddr.IPv4));
678 }
679 else
680 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
681
682 return VINF_SUCCESS;
683}
684
685
686/*
687 * new function to allow both ipv4 and ipv6 addresses to be resolved.
688 * breaks compatibility with windows before 2000
689 * will change when the new ipv6 struct will be added
690 * temporary solution
691 */
692RTDECL(int) RTSocketGetAddrInfo(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
693{
694 AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
695 AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
696 AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
697 AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);
698
699#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
700 return VERR_NOT_SUPPORTED;
701#else
702 int rc;
703 uint8_t const *pbDummy = NULL;
704
705 struct addrinfo *pgrResults = NULL;
706 struct addrinfo *pgrResult = NULL;
707
708 if (*pcbResult < 16)
709 return VERR_NET_ADDRESS_NOT_AVAILABLE;
710
711 /* Setup the hint. */
712 struct addrinfo grHints;
713 RT_ZERO(grHints);
714 grHints.ai_socktype = 0;
715 grHints.ai_flags = 0;
716 grHints.ai_protocol = 0;
717 grHints.ai_family = AF_UNSPEC;
718 if (penmAddrType)
719 {
720 switch (*penmAddrType)
721 {
722 case RTNETADDRTYPE_INVALID:
723 /*grHints.ai_family = AF_UNSPEC;*/
724 break;
725 case RTNETADDRTYPE_IPV4:
726 grHints.ai_family = AF_INET;
727 break;
728 case RTNETADDRTYPE_IPV6:
729 grHints.ai_family = AF_INET6;
730 break;
731 default:
732 AssertFailedReturn(VERR_INVALID_PARAMETER);
733 }
734 }
735
736# ifdef RT_OS_WINDOWS
737 /*
738 * Winsock2 init
739 */
740 /** @todo someone should check if we really need 2, 2 here */
741 WORD wVersionRequested = MAKEWORD(2, 2);
742 WSADATA wsaData;
743 rc = WSAStartup(wVersionRequested, &wsaData);
744 if (wsaData.wVersion != wVersionRequested)
745 {
746 AssertMsgFailed(("Wrong winsock version\n"));
747 return VERR_NOT_SUPPORTED;
748 }
749# endif
750
751 /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
752 rc = getaddrinfo(pszHost, "", &grHints, &pgrResults);
753 if (rc != 0)
754 return VERR_NET_ADDRESS_NOT_AVAILABLE;
755
756 // return data
757 // on multiple matches return only the first one
758
759 if (!pgrResults)
760 return VERR_NET_ADDRESS_NOT_AVAILABLE;
761
762 pgrResult = pgrResults->ai_next;
763 if (!pgrResult)
764 {
765 /** @todo r=bird: Missing freeaddrinfo call? */
766 return VERR_NET_ADDRESS_NOT_AVAILABLE;
767 }
768
769 rc = VINF_SUCCESS;
770 RTNETADDRTYPE enmAddrType = RTNETADDRTYPE_INVALID;
771 size_t cchIpAddress;
772 char szIpAddress[48];
773 if (pgrResult->ai_family == AF_INET)
774 {
775 struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
776 pbDummy = (uint8_t const *)&pgrSa->sin_addr;
777 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress), "%u.%u.%u.%u",
778 pbDummy[0], pbDummy[1], pbDummy[2], pbDummy[3]);
779 Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
780 enmAddrType = RTNETADDRTYPE_IPV4;
781 }
782 else if (pgrResult->ai_family == AF_INET6)
783 {
784 struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
785 pbDummy = (uint8_t const *) &pgrSa6->sin6_addr;
786 char szTmp[32+1];
787 size_t cchTmp = RTStrPrintf(szTmp, sizeof(szTmp),
788 "%02x%02x%02x%02x"
789 "%02x%02x%02x%02x"
790 "%02x%02x%02x%02x"
791 "%02x%02x%02x%02x",
792 pbDummy[0], pbDummy[1], pbDummy[2], pbDummy[3],
793 pbDummy[4], pbDummy[5], pbDummy[6], pbDummy[7],
794 pbDummy[8], pbDummy[9], pbDummy[10], pbDummy[11],
795 pbDummy[12], pbDummy[13], pbDummy[14], pbDummy[15]);
796 Assert(cchTmp == 32);
797 rc = rtStrToIpAddr6Str(szTmp, szIpAddress, sizeof(szIpAddress), NULL, 0, true);
798 if (RT_SUCCESS(rc))
799 cchIpAddress = strlen(szIpAddress);
800 else
801 {
802 szIpAddress[0] = '\0';
803 cchIpAddress = 0;
804 }
805 enmAddrType = RTNETADDRTYPE_IPV6;
806 }
807 else
808 {
809 rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
810 szIpAddress[0] = '\0';
811 cchIpAddress = 0;
812 }
813 freeaddrinfo(pgrResults);
814
815 /*
816 * Copy out the result.
817 */
818 size_t const cbResult = *pcbResult;
819 *pcbResult = cchIpAddress + 1;
820 if (cchIpAddress < cbResult)
821 memcpy(pszResult, szIpAddress, cchIpAddress + 1);
822 else
823 {
824 RT_BZERO(pszResult, cbResult);
825 if (RT_SUCCESS(rc))
826 rc = VERR_BUFFER_OVERFLOW;
827 }
828 if (penmAddrType && RT_SUCCESS(rc))
829 *penmAddrType = enmAddrType;
830 return rc;
831#endif /* !RT_OS_OS2 */
832}
833
834
835RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
836{
837 /*
838 * Validate input.
839 */
840 RTSOCKETINT *pThis = hSocket;
841 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
842 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
843 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
844 AssertPtr(pvBuffer);
845 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
846
847 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
848 if (RT_FAILURE(rc))
849 return rc;
850
851 /*
852 * Read loop.
853 * If pcbRead is NULL we have to fill the entire buffer!
854 */
855 size_t cbRead = 0;
856 size_t cbToRead = cbBuffer;
857 for (;;)
858 {
859 rtSocketErrorReset();
860#ifdef RT_OS_WINDOWS
861 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
862#else
863 size_t cbNow = cbToRead;
864#endif
865 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
866 if (cbBytesRead <= 0)
867 {
868 rc = rtSocketError();
869 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
870 if (RT_SUCCESS_NP(rc))
871 {
872 if (!pcbRead)
873 rc = VERR_NET_SHUTDOWN;
874 else
875 {
876 *pcbRead = 0;
877 rc = VINF_SUCCESS;
878 }
879 }
880 break;
881 }
882 if (pcbRead)
883 {
884 /* return partial data */
885 *pcbRead = cbBytesRead;
886 break;
887 }
888
889 /* read more? */
890 cbRead += cbBytesRead;
891 if (cbRead == cbBuffer)
892 break;
893
894 /* next */
895 cbToRead = cbBuffer - cbRead;
896 }
897
898 rtSocketUnlock(pThis);
899 return rc;
900}
901
902
903RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
904{
905 /*
906 * Validate input.
907 */
908 RTSOCKETINT *pThis = hSocket;
909 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
910 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
911 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
912 AssertPtr(pvBuffer);
913 AssertPtr(pcbRead);
914 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
915
916 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
917 if (RT_FAILURE(rc))
918 return rc;
919
920 /*
921 * Read data.
922 */
923 size_t cbRead = 0;
924 size_t cbToRead = cbBuffer;
925 rtSocketErrorReset();
926 RTSOCKADDRUNION u;
927#ifdef RT_OS_WINDOWS
928 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
929 int cbAddr = sizeof(u);
930#else
931 size_t cbNow = cbToRead;
932 socklen_t cbAddr = sizeof(u);
933#endif
934 ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
935 if (cbBytesRead <= 0)
936 {
937 rc = rtSocketError();
938 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
939 if (RT_SUCCESS_NP(rc))
940 {
941 *pcbRead = 0;
942 rc = VINF_SUCCESS;
943 }
944 }
945 else
946 {
947 if (pSrcAddr)
948 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
949 *pcbRead = cbBytesRead;
950 }
951
952 rtSocketUnlock(pThis);
953 return rc;
954}
955
956
957RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
958{
959 /*
960 * Validate input.
961 */
962 RTSOCKETINT *pThis = hSocket;
963 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
964 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
965 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
966
967 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
968 if (RT_FAILURE(rc))
969 return rc;
970
971 /*
972 * Try write all at once.
973 */
974#ifdef RT_OS_WINDOWS
975 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
976#else
977 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
978#endif
979 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
980 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
981 rc = VINF_SUCCESS;
982 else if (cbWritten < 0)
983 rc = rtSocketError();
984 else
985 {
986 /*
987 * Unfinished business, write the remainder of the request. Must ignore
988 * VERR_INTERRUPTED here if we've managed to send something.
989 */
990 size_t cbSentSoFar = 0;
991 for (;;)
992 {
993 /* advance */
994 cbBuffer -= (size_t)cbWritten;
995 if (!cbBuffer)
996 break;
997 cbSentSoFar += (size_t)cbWritten;
998 pvBuffer = (char const *)pvBuffer + cbWritten;
999
1000 /* send */
1001#ifdef RT_OS_WINDOWS
1002 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
1003#else
1004 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1005#endif
1006 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1007 if (cbWritten >= 0)
1008 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
1009 cbWritten, cbBuffer, rtSocketError()));
1010 else
1011 {
1012 rc = rtSocketError();
1013 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
1014 break;
1015 cbWritten = 0;
1016 rc = VINF_SUCCESS;
1017 }
1018 }
1019 }
1020
1021 rtSocketUnlock(pThis);
1022 return rc;
1023}
1024
1025
1026RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1027{
1028 /*
1029 * Validate input.
1030 */
1031 RTSOCKETINT *pThis = hSocket;
1032 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1033 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1034
1035 /* no locking since UDP reads may be done concurrently to writes, and
1036 * this is the normal use case of this code. */
1037
1038 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1039 if (RT_FAILURE(rc))
1040 return rc;
1041
1042 /* Figure out destination address. */
1043 struct sockaddr *pSA = NULL;
1044#ifdef RT_OS_WINDOWS
1045 int cbSA = 0;
1046#else
1047 socklen_t cbSA = 0;
1048#endif
1049 RTSOCKADDRUNION u;
1050 if (pAddr)
1051 {
1052 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1053 if (RT_FAILURE(rc))
1054 return rc;
1055 pSA = &u.Addr;
1056 cbSA = sizeof(u);
1057 }
1058
1059 /*
1060 * Must write all at once, otherwise it is a failure.
1061 */
1062#ifdef RT_OS_WINDOWS
1063 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
1064#else
1065 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1066#endif
1067 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1068 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1069 rc = VINF_SUCCESS;
1070 else if (cbWritten < 0)
1071 rc = rtSocketError();
1072 else
1073 rc = VERR_TOO_MUCH_DATA;
1074
1075 rtSocketUnlock(pThis);
1076 return rc;
1077}
1078
1079
1080RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
1081{
1082 /*
1083 * Validate input.
1084 */
1085 RTSOCKETINT *pThis = hSocket;
1086 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1087 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1088 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1089 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1090 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1091
1092 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1093 if (RT_FAILURE(rc))
1094 return rc;
1095
1096 /*
1097 * Construct message descriptor (translate pSgBuf) and send it.
1098 */
1099 rc = VERR_NO_TMP_MEMORY;
1100#ifdef RT_OS_WINDOWS
1101 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
1102 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1103
1104 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
1105 if (paMsg)
1106 {
1107 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1108 {
1109 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
1110 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
1111 }
1112
1113 DWORD dwSent;
1114 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
1115 MSG_NOSIGNAL, NULL, NULL);
1116 if (!hrc)
1117 rc = VINF_SUCCESS;
1118/** @todo check for incomplete writes */
1119 else
1120 rc = rtSocketError();
1121
1122 RTMemTmpFree(paMsg);
1123 }
1124
1125#else /* !RT_OS_WINDOWS */
1126 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
1127 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1128 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
1129
1130 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
1131 if (paMsg)
1132 {
1133 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1134 {
1135 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
1136 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
1137 }
1138
1139 struct msghdr msgHdr;
1140 RT_ZERO(msgHdr);
1141 msgHdr.msg_iov = paMsg;
1142 msgHdr.msg_iovlen = pSgBuf->cSegs;
1143 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1144 if (RT_LIKELY(cbWritten >= 0))
1145 rc = VINF_SUCCESS;
1146/** @todo check for incomplete writes */
1147 else
1148 rc = rtSocketError();
1149
1150 RTMemTmpFree(paMsg);
1151 }
1152#endif /* !RT_OS_WINDOWS */
1153
1154 rtSocketUnlock(pThis);
1155 return rc;
1156}
1157
1158
1159RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1160{
1161 va_list va;
1162 va_start(va, cSegs);
1163 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1164 va_end(va);
1165 return rc;
1166}
1167
1168
1169RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1170{
1171 /*
1172 * Set up a S/G segment array + buffer on the stack and pass it
1173 * on to RTSocketSgWrite.
1174 */
1175 Assert(cSegs <= 16);
1176 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1177 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1178 for (size_t i = 0; i < cSegs; i++)
1179 {
1180 paSegs[i].pvSeg = va_arg(va, void *);
1181 paSegs[i].cbSeg = va_arg(va, size_t);
1182 }
1183
1184 RTSGBUF SgBuf;
1185 RTSgBufInit(&SgBuf, paSegs, cSegs);
1186 return RTSocketSgWrite(hSocket, &SgBuf);
1187}
1188
1189
1190RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1191{
1192 /*
1193 * Validate input.
1194 */
1195 RTSOCKETINT *pThis = hSocket;
1196 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1197 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1198 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1199 AssertPtr(pvBuffer);
1200 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
1201 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1202
1203 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1204 if (RT_FAILURE(rc))
1205 return rc;
1206
1207 rtSocketErrorReset();
1208#ifdef RT_OS_WINDOWS
1209 int cbNow = cbBuffer >= INT_MAX/2 ? INT_MAX/2 : (int)cbBuffer;
1210
1211 int cbRead = recv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1212 if (cbRead >= 0)
1213 {
1214 *pcbRead = cbRead;
1215 rc = VINF_SUCCESS;
1216 }
1217 else
1218 rc = rtSocketError();
1219
1220 if (rc == VERR_TRY_AGAIN)
1221 rc = VINF_TRY_AGAIN;
1222#else
1223 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1224 if (cbRead >= 0)
1225 *pcbRead = cbRead;
1226 else if (errno == EAGAIN)
1227 {
1228 *pcbRead = 0;
1229 rc = VINF_TRY_AGAIN;
1230 }
1231 else
1232 rc = rtSocketError();
1233#endif
1234
1235 rtSocketUnlock(pThis);
1236 return rc;
1237}
1238
1239
1240RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1241{
1242 /*
1243 * Validate input.
1244 */
1245 RTSOCKETINT *pThis = hSocket;
1246 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1247 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1248 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1249 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1250
1251 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1252 if (RT_FAILURE(rc))
1253 return rc;
1254
1255 rtSocketErrorReset();
1256#ifdef RT_OS_WINDOWS
1257 int cbNow = RT_MIN((int)cbBuffer, INT_MAX/2);
1258
1259 int cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1260
1261 if (cbWritten >= 0)
1262 {
1263 *pcbWritten = cbWritten;
1264 rc = VINF_SUCCESS;
1265 }
1266 else
1267 rc = rtSocketError();
1268
1269 if (rc == VERR_TRY_AGAIN)
1270 rc = VINF_TRY_AGAIN;
1271#else
1272 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1273 if (cbWritten >= 0)
1274 *pcbWritten = cbWritten;
1275 else if (errno == EAGAIN)
1276 {
1277 *pcbWritten = 0;
1278 rc = VINF_TRY_AGAIN;
1279 }
1280 else
1281 rc = rtSocketError();
1282#endif
1283
1284 rtSocketUnlock(pThis);
1285 return rc;
1286}
1287
1288
1289RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1290{
1291 /*
1292 * Validate input.
1293 */
1294 RTSOCKETINT *pThis = hSocket;
1295 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1296 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1297 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1298 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1299 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1300 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1301
1302 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1303 if (RT_FAILURE(rc))
1304 return rc;
1305
1306 unsigned cSegsToSend = 0;
1307 rc = VERR_NO_TMP_MEMORY;
1308#ifdef RT_OS_WINDOWS
1309 LPWSABUF paMsg = NULL;
1310
1311 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1312 if (paMsg)
1313 {
1314 DWORD dwSent = 0;
1315 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
1316 MSG_NOSIGNAL, NULL, NULL);
1317 if (!hrc)
1318 rc = VINF_SUCCESS;
1319 else
1320 rc = rtSocketError();
1321
1322 *pcbWritten = dwSent;
1323
1324 RTMemTmpFree(paMsg);
1325 }
1326
1327#else /* !RT_OS_WINDOWS */
1328 struct iovec *paMsg = NULL;
1329
1330 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1331 if (paMsg)
1332 {
1333 struct msghdr msgHdr;
1334 RT_ZERO(msgHdr);
1335 msgHdr.msg_iov = paMsg;
1336 msgHdr.msg_iovlen = cSegsToSend;
1337 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1338 if (RT_LIKELY(cbWritten >= 0))
1339 {
1340 rc = VINF_SUCCESS;
1341 *pcbWritten = cbWritten;
1342 }
1343 else
1344 rc = rtSocketError();
1345
1346 RTMemTmpFree(paMsg);
1347 }
1348#endif /* !RT_OS_WINDOWS */
1349
1350 rtSocketUnlock(pThis);
1351 return rc;
1352}
1353
1354
1355RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1356{
1357 va_list va;
1358 va_start(va, pcbWritten);
1359 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1360 va_end(va);
1361 return rc;
1362}
1363
1364
1365RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1366{
1367 /*
1368 * Set up a S/G segment array + buffer on the stack and pass it
1369 * on to RTSocketSgWrite.
1370 */
1371 Assert(cSegs <= 16);
1372 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1373 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1374 for (size_t i = 0; i < cSegs; i++)
1375 {
1376 paSegs[i].pvSeg = va_arg(va, void *);
1377 paSegs[i].cbSeg = va_arg(va, size_t);
1378 }
1379
1380 RTSGBUF SgBuf;
1381 RTSgBufInit(&SgBuf, paSegs, cSegs);
1382 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1383}
1384
1385
1386RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1387{
1388 /*
1389 * Validate input.
1390 */
1391 RTSOCKETINT *pThis = hSocket;
1392 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1393 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1394 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1395 int const fdMax = (int)pThis->hNative + 1;
1396 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1397
1398 /*
1399 * Set up the file descriptor sets and do the select.
1400 */
1401 fd_set fdsetR;
1402 FD_ZERO(&fdsetR);
1403 FD_SET(pThis->hNative, &fdsetR);
1404
1405 fd_set fdsetE = fdsetR;
1406
1407 int rc;
1408 if (cMillies == RT_INDEFINITE_WAIT)
1409 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1410 else
1411 {
1412 struct timeval timeout;
1413 timeout.tv_sec = cMillies / 1000;
1414 timeout.tv_usec = (cMillies % 1000) * 1000;
1415 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1416 }
1417 if (rc > 0)
1418 rc = VINF_SUCCESS;
1419 else if (rc == 0)
1420 rc = VERR_TIMEOUT;
1421 else
1422 rc = rtSocketError();
1423
1424 return rc;
1425}
1426
1427
1428RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents,
1429 RTMSINTERVAL cMillies)
1430{
1431 /*
1432 * Validate input.
1433 */
1434 RTSOCKETINT *pThis = hSocket;
1435 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1436 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1437 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
1438 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
1439 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1440 int const fdMax = (int)pThis->hNative + 1;
1441 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1442
1443 *pfEvents = 0;
1444
1445 /*
1446 * Set up the file descriptor sets and do the select.
1447 */
1448 fd_set fdsetR;
1449 fd_set fdsetW;
1450 fd_set fdsetE;
1451 FD_ZERO(&fdsetR);
1452 FD_ZERO(&fdsetW);
1453 FD_ZERO(&fdsetE);
1454
1455 if (fEvents & RTSOCKET_EVT_READ)
1456 FD_SET(pThis->hNative, &fdsetR);
1457 if (fEvents & RTSOCKET_EVT_WRITE)
1458 FD_SET(pThis->hNative, &fdsetW);
1459 if (fEvents & RTSOCKET_EVT_ERROR)
1460 FD_SET(pThis->hNative, &fdsetE);
1461
1462 int rc;
1463 if (cMillies == RT_INDEFINITE_WAIT)
1464 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1465 else
1466 {
1467 struct timeval timeout;
1468 timeout.tv_sec = cMillies / 1000;
1469 timeout.tv_usec = (cMillies % 1000) * 1000;
1470 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1471 }
1472 if (rc > 0)
1473 {
1474 if (FD_ISSET(pThis->hNative, &fdsetR))
1475 *pfEvents |= RTSOCKET_EVT_READ;
1476 if (FD_ISSET(pThis->hNative, &fdsetW))
1477 *pfEvents |= RTSOCKET_EVT_WRITE;
1478 if (FD_ISSET(pThis->hNative, &fdsetE))
1479 *pfEvents |= RTSOCKET_EVT_ERROR;
1480
1481 rc = VINF_SUCCESS;
1482 }
1483 else if (rc == 0)
1484 rc = VERR_TIMEOUT;
1485 else
1486 rc = rtSocketError();
1487
1488 return rc;
1489}
1490
1491
1492RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1493{
1494 /*
1495 * Validate input, don't lock it because we might want to interrupt a call
1496 * active on a different thread.
1497 */
1498 RTSOCKETINT *pThis = hSocket;
1499 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1500 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1501 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1502 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1503
1504 /*
1505 * Do the job.
1506 */
1507 int rc = VINF_SUCCESS;
1508 int fHow;
1509 if (fRead && fWrite)
1510 fHow = SHUT_RDWR;
1511 else if (fRead)
1512 fHow = SHUT_RD;
1513 else
1514 fHow = SHUT_WR;
1515 if (shutdown(pThis->hNative, fHow) == -1)
1516 rc = rtSocketError();
1517
1518 return rc;
1519}
1520
1521
1522RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1523{
1524 /*
1525 * Validate input.
1526 */
1527 RTSOCKETINT *pThis = hSocket;
1528 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1529 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1530 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1531
1532 /*
1533 * Get the address and convert it.
1534 */
1535 int rc;
1536 RTSOCKADDRUNION u;
1537#ifdef RT_OS_WINDOWS
1538 int cbAddr = sizeof(u);
1539#else
1540 socklen_t cbAddr = sizeof(u);
1541#endif
1542 RT_ZERO(u);
1543 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1544 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1545 else
1546 rc = rtSocketError();
1547
1548 return rc;
1549}
1550
1551
1552RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1553{
1554 /*
1555 * Validate input.
1556 */
1557 RTSOCKETINT *pThis = hSocket;
1558 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1559 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1560 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1561
1562 /*
1563 * Get the address and convert it.
1564 */
1565 int rc;
1566 RTSOCKADDRUNION u;
1567#ifdef RT_OS_WINDOWS
1568 int cbAddr = sizeof(u);
1569#else
1570 socklen_t cbAddr = sizeof(u);
1571#endif
1572 RT_ZERO(u);
1573 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1574 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1575 else
1576 rc = rtSocketError();
1577
1578 return rc;
1579}
1580
1581
1582
1583/**
1584 * Wrapper around bind.
1585 *
1586 * @returns IPRT status code.
1587 * @param hSocket The socket handle.
1588 * @param pAddr The address to bind to.
1589 */
1590int rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1591{
1592 /*
1593 * Validate input.
1594 */
1595 RTSOCKETINT *pThis = hSocket;
1596 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1597 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1598 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1599
1600 RTSOCKADDRUNION u;
1601 int cbAddr;
1602 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1603 if (RT_SUCCESS(rc))
1604 {
1605 if (bind(pThis->hNative, &u.Addr, cbAddr) != 0)
1606 rc = rtSocketError();
1607 }
1608
1609 rtSocketUnlock(pThis);
1610 return rc;
1611}
1612
1613
1614/**
1615 * Wrapper around listen.
1616 *
1617 * @returns IPRT status code.
1618 * @param hSocket The socket handle.
1619 * @param cMaxPending The max number of pending connections.
1620 */
1621int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1622{
1623 /*
1624 * Validate input.
1625 */
1626 RTSOCKETINT *pThis = hSocket;
1627 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1628 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1629 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1630
1631 int rc = VINF_SUCCESS;
1632 if (listen(pThis->hNative, cMaxPending) != 0)
1633 rc = rtSocketError();
1634
1635 rtSocketUnlock(pThis);
1636 return rc;
1637}
1638
1639
1640/**
1641 * Wrapper around accept.
1642 *
1643 * @returns IPRT status code.
1644 * @param hSocket The socket handle.
1645 * @param phClient Where to return the client socket handle on
1646 * success.
1647 * @param pAddr Where to return the client address.
1648 * @param pcbAddr On input this gives the size buffer size of what
1649 * @a pAddr point to. On return this contains the
1650 * size of what's stored at @a pAddr.
1651 */
1652int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1653{
1654 /*
1655 * Validate input.
1656 * Only lock the socket temporarily while we get the native handle, so that
1657 * we can safely shutdown and destroy the socket from a different thread.
1658 */
1659 RTSOCKETINT *pThis = hSocket;
1660 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1661 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1662 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1663
1664 /*
1665 * Call accept().
1666 */
1667 rtSocketErrorReset();
1668 int rc = VINF_SUCCESS;
1669#ifdef RT_OS_WINDOWS
1670 int cbAddr = (int)*pcbAddr;
1671#else
1672 socklen_t cbAddr = *pcbAddr;
1673#endif
1674 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1675 if (hNativeClient != NIL_RTSOCKETNATIVE)
1676 {
1677 *pcbAddr = cbAddr;
1678
1679 /*
1680 * Wrap the client socket.
1681 */
1682 rc = rtSocketCreateForNative(phClient, hNativeClient);
1683 if (RT_FAILURE(rc))
1684 {
1685#ifdef RT_OS_WINDOWS
1686 closesocket(hNativeClient);
1687#else
1688 close(hNativeClient);
1689#endif
1690 }
1691 }
1692 else
1693 rc = rtSocketError();
1694
1695 rtSocketUnlock(pThis);
1696 return rc;
1697}
1698
1699
1700/**
1701 * Wrapper around connect.
1702 *
1703 * @returns IPRT status code.
1704 * @param hSocket The socket handle.
1705 * @param pAddr The socket address to connect to.
1706 */
1707int rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr)
1708{
1709 /*
1710 * Validate input.
1711 */
1712 RTSOCKETINT *pThis = hSocket;
1713 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1714 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1715 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1716
1717 RTSOCKADDRUNION u;
1718 int cbAddr;
1719 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1720 if (RT_SUCCESS(rc))
1721 {
1722 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1723 rc = rtSocketError();
1724 }
1725
1726 rtSocketUnlock(pThis);
1727 return rc;
1728}
1729
1730
1731/**
1732 * Wrapper around setsockopt.
1733 *
1734 * @returns IPRT status code.
1735 * @param hSocket The socket handle.
1736 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1737 * @param iOption The option, e.g. TCP_NODELAY.
1738 * @param pvValue The value buffer.
1739 * @param cbValue The size of the value pointed to by pvValue.
1740 */
1741int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1742{
1743 /*
1744 * Validate input.
1745 */
1746 RTSOCKETINT *pThis = hSocket;
1747 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1748 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1749 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1750
1751 int rc = VINF_SUCCESS;
1752 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1753 rc = rtSocketError();
1754
1755 rtSocketUnlock(pThis);
1756 return rc;
1757}
1758
1759#ifdef RT_OS_WINDOWS
1760
1761/**
1762 * Internal RTPollSetAdd helper that returns the handle that should be added to
1763 * the pollset.
1764 *
1765 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1766 * @param hSocket The socket handle.
1767 * @param fEvents The events we're polling for.
1768 * @param ph where to put the primary handle.
1769 */
1770int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1771{
1772 RTSOCKETINT *pThis = hSocket;
1773 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1774 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1775 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1776
1777 int rc = VINF_SUCCESS;
1778 if (pThis->hEvent != WSA_INVALID_EVENT)
1779 *ph = pThis->hEvent;
1780 else
1781 {
1782 *ph = pThis->hEvent = WSACreateEvent();
1783 if (pThis->hEvent == WSA_INVALID_EVENT)
1784 rc = rtSocketError();
1785 }
1786
1787 rtSocketUnlock(pThis);
1788 return rc;
1789}
1790
1791
1792/**
1793 * Undos the harm done by WSAEventSelect.
1794 *
1795 * @returns IPRT status code.
1796 * @param pThis The socket handle.
1797 */
1798static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1799{
1800 int rc = VINF_SUCCESS;
1801 if (pThis->fSubscribedEvts)
1802 {
1803 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1804 {
1805 pThis->fSubscribedEvts = 0;
1806
1807 /*
1808 * Switch back to blocking mode if that was the state before the
1809 * operation.
1810 */
1811 if (pThis->fBlocking)
1812 {
1813 u_long fNonBlocking = 0;
1814 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1815 if (rc2 != 0)
1816 {
1817 rc = rtSocketError();
1818 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1819 }
1820 }
1821 }
1822 else
1823 {
1824 rc = rtSocketError();
1825 AssertMsgFailed(("%Rrc\n", rc));
1826 }
1827 }
1828 return rc;
1829}
1830
1831
1832/**
1833 * Updates the mask of events we're subscribing to.
1834 *
1835 * @returns IPRT status code.
1836 * @param pThis The socket handle.
1837 * @param fEvents The events we want to subscribe to.
1838 */
1839static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1840{
1841 LONG fNetworkEvents = 0;
1842 if (fEvents & RTPOLL_EVT_READ)
1843 fNetworkEvents |= FD_READ;
1844 if (fEvents & RTPOLL_EVT_WRITE)
1845 fNetworkEvents |= FD_WRITE;
1846 if (fEvents & RTPOLL_EVT_ERROR)
1847 fNetworkEvents |= FD_CLOSE;
1848 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
1849 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1850 {
1851 pThis->fSubscribedEvts = fEvents;
1852 return VINF_SUCCESS;
1853 }
1854
1855 int rc = rtSocketError();
1856 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1857 return rc;
1858}
1859
1860
1861/**
1862 * Checks for pending events.
1863 *
1864 * @returns Event mask or 0.
1865 * @param pThis The socket handle.
1866 * @param fEvents The desired events.
1867 */
1868static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1869{
1870 int rc = VINF_SUCCESS;
1871 uint32_t fRetEvents = 0;
1872
1873 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
1874
1875 /* Make sure WSAEnumNetworkEvents returns what we want. */
1876 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1877 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1878
1879 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1880 WSANETWORKEVENTS NetEvts;
1881 RT_ZERO(NetEvts);
1882 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1883 {
1884 if ( (NetEvts.lNetworkEvents & FD_READ)
1885 && (fEvents & RTPOLL_EVT_READ)
1886 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1887 fRetEvents |= RTPOLL_EVT_READ;
1888
1889 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1890 && (fEvents & RTPOLL_EVT_WRITE)
1891 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1892 fRetEvents |= RTPOLL_EVT_WRITE;
1893
1894 if (fEvents & RTPOLL_EVT_ERROR)
1895 {
1896 if (NetEvts.lNetworkEvents & FD_CLOSE)
1897 fRetEvents |= RTPOLL_EVT_ERROR;
1898 else
1899 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1900 if ( (NetEvts.lNetworkEvents & (1L << i))
1901 && NetEvts.iErrorCode[i] != 0)
1902 fRetEvents |= RTPOLL_EVT_ERROR;
1903 }
1904 }
1905 else
1906 rc = rtSocketError();
1907
1908 /* Fall back on select if we hit an error above. */
1909 if (RT_FAILURE(rc))
1910 {
1911 /** @todo */
1912 }
1913
1914 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
1915 return fRetEvents;
1916}
1917
1918
1919/**
1920 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1921 * clear, starts whatever actions we've got running during the poll call.
1922 *
1923 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1924 * Event mask (in @a fEvents) and no actions if the handle is ready
1925 * already.
1926 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1927 * different poll set.
1928 *
1929 * @param hSocket The socket handle.
1930 * @param hPollSet The poll set handle (for access checks).
1931 * @param fEvents The events we're polling for.
1932 * @param fFinalEntry Set if this is the final entry for this handle
1933 * in this poll set. This can be used for dealing
1934 * with duplicate entries.
1935 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1936 * we'll wait for an event to occur.
1937 *
1938 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1939 * @c true, we don't currently care about that oddity...
1940 */
1941uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1942{
1943 RTSOCKETINT *pThis = hSocket;
1944 AssertPtrReturn(pThis, UINT32_MAX);
1945 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1946 if (rtSocketTryLock(pThis))
1947 pThis->hPollSet = hPollSet;
1948 else
1949 {
1950 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1951 ASMAtomicIncU32(&pThis->cUsers);
1952 }
1953
1954 /* (rtSocketPollCheck will reset the event object). */
1955 uint32_t fRetEvents = pThis->fEventsSaved;
1956 pThis->fEventsSaved = 0; /* Reset */
1957 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
1958
1959 if ( !fRetEvents
1960 && !fNoWait)
1961 {
1962 pThis->fPollEvts |= fEvents;
1963 if ( fFinalEntry
1964 && pThis->fSubscribedEvts != pThis->fPollEvts)
1965 {
1966 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1967 if (RT_FAILURE(rc))
1968 {
1969 pThis->fPollEvts = 0;
1970 fRetEvents = UINT32_MAX;
1971 }
1972 }
1973 }
1974
1975 if (fRetEvents || fNoWait)
1976 {
1977 if (pThis->cUsers == 1)
1978 {
1979 rtSocketPollClearEventAndRestoreBlocking(pThis);
1980 pThis->hPollSet = NIL_RTPOLLSET;
1981 }
1982 ASMAtomicDecU32(&pThis->cUsers);
1983 }
1984
1985 return fRetEvents;
1986}
1987
1988
1989/**
1990 * Called after a WaitForMultipleObjects returned in order to check for pending
1991 * events and stop whatever actions that rtSocketPollStart() initiated.
1992 *
1993 * @returns Event mask or 0.
1994 *
1995 * @param hSocket The socket handle.
1996 * @param fEvents The events we're polling for.
1997 * @param fFinalEntry Set if this is the final entry for this handle
1998 * in this poll set. This can be used for dealing
1999 * with duplicate entries. Only keep in mind that
2000 * this method is called in reverse order, so the
2001 * first call will have this set (when the entire
2002 * set was processed).
2003 * @param fHarvestEvents Set if we should check for pending events.
2004 */
2005uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2006{
2007 RTSOCKETINT *pThis = hSocket;
2008 AssertPtrReturn(pThis, 0);
2009 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2010 Assert(pThis->cUsers > 0);
2011 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2012
2013 /* Harvest events and clear the event mask for the next round of polling. */
2014 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2015 pThis->fPollEvts = 0;
2016
2017 /*
2018 * Save the write event if required.
2019 * It is only posted once and might get lost if the another source in the
2020 * pollset with a higher priority has pending events.
2021 */
2022 if ( !fHarvestEvents
2023 && fRetEvents)
2024 {
2025 pThis->fEventsSaved = fRetEvents;
2026 fRetEvents = 0;
2027 }
2028
2029 /* Make the socket blocking again and unlock the handle. */
2030 if (pThis->cUsers == 1)
2031 {
2032 rtSocketPollClearEventAndRestoreBlocking(pThis);
2033 pThis->hPollSet = NIL_RTPOLLSET;
2034 }
2035 ASMAtomicDecU32(&pThis->cUsers);
2036 return fRetEvents;
2037}
2038
2039#endif /* RT_OS_WINDOWS */
Note: See TracBrowser for help on using the repository browser.

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