VirtualBox

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

Last change on this file since 43213 was 43213, checked in by vboxsync, 12 years ago

RTSocketGetAddrInfo -> RTSocketQueryAddressStr

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 58.1 KB
Line 
1/* $Id: socket.cpp 43213 2012-09-06 08:37:56Z 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.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 <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 */
690RTDECL(int) RTSocketQueryAddressStr(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
691{
692 AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
693 AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
694 AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
695 AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);
696
697#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
698 return VERR_NOT_SUPPORTED;
699
700#else
701 int rc;
702 if (*pcbResult < 16)
703 return VERR_NET_ADDRESS_NOT_AVAILABLE;
704
705 /* Setup the hint. */
706 struct addrinfo grHints;
707 RT_ZERO(grHints);
708 grHints.ai_socktype = 0;
709 grHints.ai_flags = 0;
710 grHints.ai_protocol = 0;
711 grHints.ai_family = AF_UNSPEC;
712 if (penmAddrType)
713 {
714 switch (*penmAddrType)
715 {
716 case RTNETADDRTYPE_INVALID:
717 /*grHints.ai_family = AF_UNSPEC;*/
718 break;
719 case RTNETADDRTYPE_IPV4:
720 grHints.ai_family = AF_INET;
721 break;
722 case RTNETADDRTYPE_IPV6:
723 grHints.ai_family = AF_INET6;
724 break;
725 default:
726 AssertFailedReturn(VERR_INVALID_PARAMETER);
727 }
728 }
729
730# ifdef RT_OS_WINDOWS
731 /*
732 * Winsock2 init
733 */
734 /** @todo someone should check if we really need 2, 2 here */
735 WORD wVersionRequested = MAKEWORD(2, 2);
736 WSADATA wsaData;
737 rc = WSAStartup(wVersionRequested, &wsaData);
738 if (wsaData.wVersion != wVersionRequested)
739 {
740 AssertMsgFailed(("Wrong winsock version\n"));
741 return VERR_NOT_SUPPORTED;
742 }
743# endif
744
745 /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
746 struct addrinfo *pgrResults = NULL;
747 rc = getaddrinfo(pszHost, "", &grHints, &pgrResults);
748 if (rc != 0)
749 return VERR_NET_ADDRESS_NOT_AVAILABLE;
750
751 // return data
752 // on multiple matches return only the first one
753
754 if (!pgrResults)
755 return VERR_NET_ADDRESS_NOT_AVAILABLE;
756
757 struct addrinfo const *pgrResult = pgrResults->ai_next;
758 if (!pgrResult)
759 {
760 freeaddrinfo(pgrResults);
761 return VERR_NET_ADDRESS_NOT_AVAILABLE;
762 }
763
764 uint8_t const *pbDummy;
765 RTNETADDRTYPE enmAddrType = RTNETADDRTYPE_INVALID;
766 size_t cchIpAddress;
767 char szIpAddress[48];
768 if (pgrResult->ai_family == AF_INET)
769 {
770 struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
771 pbDummy = (uint8_t const *)&pgrSa->sin_addr;
772 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress), "%u.%u.%u.%u",
773 pbDummy[0], pbDummy[1], pbDummy[2], pbDummy[3]);
774 Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
775 enmAddrType = RTNETADDRTYPE_IPV4;
776 rc = VINF_SUCCESS;
777 }
778 else if (pgrResult->ai_family == AF_INET6)
779 {
780 struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
781 pbDummy = (uint8_t const *) &pgrSa6->sin6_addr;
782 char szTmp[32+1];
783 size_t cchTmp = RTStrPrintf(szTmp, sizeof(szTmp),
784 "%02x%02x%02x%02x"
785 "%02x%02x%02x%02x"
786 "%02x%02x%02x%02x"
787 "%02x%02x%02x%02x",
788 pbDummy[0], pbDummy[1], pbDummy[2], pbDummy[3],
789 pbDummy[4], pbDummy[5], pbDummy[6], pbDummy[7],
790 pbDummy[8], pbDummy[9], pbDummy[10], pbDummy[11],
791 pbDummy[12], pbDummy[13], pbDummy[14], pbDummy[15]);
792 Assert(cchTmp == 32);
793 rc = rtStrToIpAddr6Str(szTmp, szIpAddress, sizeof(szIpAddress), NULL, 0, true);
794 if (RT_SUCCESS(rc))
795 cchIpAddress = strlen(szIpAddress);
796 else
797 {
798 szIpAddress[0] = '\0';
799 cchIpAddress = 0;
800 }
801 enmAddrType = RTNETADDRTYPE_IPV6;
802 }
803 else
804 {
805 rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
806 szIpAddress[0] = '\0';
807 cchIpAddress = 0;
808 }
809 freeaddrinfo(pgrResults);
810
811 /*
812 * Copy out the result.
813 */
814 size_t const cbResult = *pcbResult;
815 *pcbResult = cchIpAddress + 1;
816 if (cchIpAddress < cbResult)
817 memcpy(pszResult, szIpAddress, cchIpAddress + 1);
818 else
819 {
820 RT_BZERO(pszResult, cbResult);
821 if (RT_SUCCESS(rc))
822 rc = VERR_BUFFER_OVERFLOW;
823 }
824 if (penmAddrType && RT_SUCCESS(rc))
825 *penmAddrType = enmAddrType;
826 return rc;
827#endif /* !RT_OS_OS2 */
828}
829
830
831RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
832{
833 /*
834 * Validate input.
835 */
836 RTSOCKETINT *pThis = hSocket;
837 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
838 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
839 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
840 AssertPtr(pvBuffer);
841 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
842
843 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
844 if (RT_FAILURE(rc))
845 return rc;
846
847 /*
848 * Read loop.
849 * If pcbRead is NULL we have to fill the entire buffer!
850 */
851 size_t cbRead = 0;
852 size_t cbToRead = cbBuffer;
853 for (;;)
854 {
855 rtSocketErrorReset();
856#ifdef RT_OS_WINDOWS
857 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
858#else
859 size_t cbNow = cbToRead;
860#endif
861 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
862 if (cbBytesRead <= 0)
863 {
864 rc = rtSocketError();
865 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
866 if (RT_SUCCESS_NP(rc))
867 {
868 if (!pcbRead)
869 rc = VERR_NET_SHUTDOWN;
870 else
871 {
872 *pcbRead = 0;
873 rc = VINF_SUCCESS;
874 }
875 }
876 break;
877 }
878 if (pcbRead)
879 {
880 /* return partial data */
881 *pcbRead = cbBytesRead;
882 break;
883 }
884
885 /* read more? */
886 cbRead += cbBytesRead;
887 if (cbRead == cbBuffer)
888 break;
889
890 /* next */
891 cbToRead = cbBuffer - cbRead;
892 }
893
894 rtSocketUnlock(pThis);
895 return rc;
896}
897
898
899RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
900{
901 /*
902 * Validate input.
903 */
904 RTSOCKETINT *pThis = hSocket;
905 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
906 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
907 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
908 AssertPtr(pvBuffer);
909 AssertPtr(pcbRead);
910 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
911
912 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
913 if (RT_FAILURE(rc))
914 return rc;
915
916 /*
917 * Read data.
918 */
919 size_t cbRead = 0;
920 size_t cbToRead = cbBuffer;
921 rtSocketErrorReset();
922 RTSOCKADDRUNION u;
923#ifdef RT_OS_WINDOWS
924 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
925 int cbAddr = sizeof(u);
926#else
927 size_t cbNow = cbToRead;
928 socklen_t cbAddr = sizeof(u);
929#endif
930 ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
931 if (cbBytesRead <= 0)
932 {
933 rc = rtSocketError();
934 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
935 if (RT_SUCCESS_NP(rc))
936 {
937 *pcbRead = 0;
938 rc = VINF_SUCCESS;
939 }
940 }
941 else
942 {
943 if (pSrcAddr)
944 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
945 *pcbRead = cbBytesRead;
946 }
947
948 rtSocketUnlock(pThis);
949 return rc;
950}
951
952
953RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
954{
955 /*
956 * Validate input.
957 */
958 RTSOCKETINT *pThis = hSocket;
959 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
960 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
961 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
962
963 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
964 if (RT_FAILURE(rc))
965 return rc;
966
967 /*
968 * Try write all at once.
969 */
970#ifdef RT_OS_WINDOWS
971 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
972#else
973 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
974#endif
975 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
976 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
977 rc = VINF_SUCCESS;
978 else if (cbWritten < 0)
979 rc = rtSocketError();
980 else
981 {
982 /*
983 * Unfinished business, write the remainder of the request. Must ignore
984 * VERR_INTERRUPTED here if we've managed to send something.
985 */
986 size_t cbSentSoFar = 0;
987 for (;;)
988 {
989 /* advance */
990 cbBuffer -= (size_t)cbWritten;
991 if (!cbBuffer)
992 break;
993 cbSentSoFar += (size_t)cbWritten;
994 pvBuffer = (char const *)pvBuffer + cbWritten;
995
996 /* send */
997#ifdef RT_OS_WINDOWS
998 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
999#else
1000 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1001#endif
1002 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1003 if (cbWritten >= 0)
1004 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
1005 cbWritten, cbBuffer, rtSocketError()));
1006 else
1007 {
1008 rc = rtSocketError();
1009 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
1010 break;
1011 cbWritten = 0;
1012 rc = VINF_SUCCESS;
1013 }
1014 }
1015 }
1016
1017 rtSocketUnlock(pThis);
1018 return rc;
1019}
1020
1021
1022RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1023{
1024 /*
1025 * Validate input.
1026 */
1027 RTSOCKETINT *pThis = hSocket;
1028 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1029 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1030
1031 /* no locking since UDP reads may be done concurrently to writes, and
1032 * this is the normal use case of this code. */
1033
1034 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1035 if (RT_FAILURE(rc))
1036 return rc;
1037
1038 /* Figure out destination address. */
1039 struct sockaddr *pSA = NULL;
1040#ifdef RT_OS_WINDOWS
1041 int cbSA = 0;
1042#else
1043 socklen_t cbSA = 0;
1044#endif
1045 RTSOCKADDRUNION u;
1046 if (pAddr)
1047 {
1048 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1049 if (RT_FAILURE(rc))
1050 return rc;
1051 pSA = &u.Addr;
1052 cbSA = sizeof(u);
1053 }
1054
1055 /*
1056 * Must write all at once, otherwise it is a failure.
1057 */
1058#ifdef RT_OS_WINDOWS
1059 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
1060#else
1061 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1062#endif
1063 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1064 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1065 rc = VINF_SUCCESS;
1066 else if (cbWritten < 0)
1067 rc = rtSocketError();
1068 else
1069 rc = VERR_TOO_MUCH_DATA;
1070
1071 rtSocketUnlock(pThis);
1072 return rc;
1073}
1074
1075
1076RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
1077{
1078 /*
1079 * Validate input.
1080 */
1081 RTSOCKETINT *pThis = hSocket;
1082 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1083 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1084 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1085 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1086 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1087
1088 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1089 if (RT_FAILURE(rc))
1090 return rc;
1091
1092 /*
1093 * Construct message descriptor (translate pSgBuf) and send it.
1094 */
1095 rc = VERR_NO_TMP_MEMORY;
1096#ifdef RT_OS_WINDOWS
1097 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
1098 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1099
1100 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
1101 if (paMsg)
1102 {
1103 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1104 {
1105 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
1106 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
1107 }
1108
1109 DWORD dwSent;
1110 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
1111 MSG_NOSIGNAL, NULL, NULL);
1112 if (!hrc)
1113 rc = VINF_SUCCESS;
1114/** @todo check for incomplete writes */
1115 else
1116 rc = rtSocketError();
1117
1118 RTMemTmpFree(paMsg);
1119 }
1120
1121#else /* !RT_OS_WINDOWS */
1122 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
1123 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1124 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
1125
1126 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
1127 if (paMsg)
1128 {
1129 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1130 {
1131 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
1132 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
1133 }
1134
1135 struct msghdr msgHdr;
1136 RT_ZERO(msgHdr);
1137 msgHdr.msg_iov = paMsg;
1138 msgHdr.msg_iovlen = pSgBuf->cSegs;
1139 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1140 if (RT_LIKELY(cbWritten >= 0))
1141 rc = VINF_SUCCESS;
1142/** @todo check for incomplete writes */
1143 else
1144 rc = rtSocketError();
1145
1146 RTMemTmpFree(paMsg);
1147 }
1148#endif /* !RT_OS_WINDOWS */
1149
1150 rtSocketUnlock(pThis);
1151 return rc;
1152}
1153
1154
1155RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1156{
1157 va_list va;
1158 va_start(va, cSegs);
1159 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1160 va_end(va);
1161 return rc;
1162}
1163
1164
1165RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1166{
1167 /*
1168 * Set up a S/G segment array + buffer on the stack and pass it
1169 * on to RTSocketSgWrite.
1170 */
1171 Assert(cSegs <= 16);
1172 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1173 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1174 for (size_t i = 0; i < cSegs; i++)
1175 {
1176 paSegs[i].pvSeg = va_arg(va, void *);
1177 paSegs[i].cbSeg = va_arg(va, size_t);
1178 }
1179
1180 RTSGBUF SgBuf;
1181 RTSgBufInit(&SgBuf, paSegs, cSegs);
1182 return RTSocketSgWrite(hSocket, &SgBuf);
1183}
1184
1185
1186RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1187{
1188 /*
1189 * Validate input.
1190 */
1191 RTSOCKETINT *pThis = hSocket;
1192 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1193 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1194 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1195 AssertPtr(pvBuffer);
1196 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
1197 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1198
1199 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1200 if (RT_FAILURE(rc))
1201 return rc;
1202
1203 rtSocketErrorReset();
1204#ifdef RT_OS_WINDOWS
1205 int cbNow = cbBuffer >= INT_MAX/2 ? INT_MAX/2 : (int)cbBuffer;
1206
1207 int cbRead = recv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1208 if (cbRead >= 0)
1209 {
1210 *pcbRead = cbRead;
1211 rc = VINF_SUCCESS;
1212 }
1213 else
1214 rc = rtSocketError();
1215
1216 if (rc == VERR_TRY_AGAIN)
1217 rc = VINF_TRY_AGAIN;
1218#else
1219 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1220 if (cbRead >= 0)
1221 *pcbRead = cbRead;
1222 else if (errno == EAGAIN)
1223 {
1224 *pcbRead = 0;
1225 rc = VINF_TRY_AGAIN;
1226 }
1227 else
1228 rc = rtSocketError();
1229#endif
1230
1231 rtSocketUnlock(pThis);
1232 return rc;
1233}
1234
1235
1236RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1237{
1238 /*
1239 * Validate input.
1240 */
1241 RTSOCKETINT *pThis = hSocket;
1242 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1243 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1244 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1245 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1246
1247 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1248 if (RT_FAILURE(rc))
1249 return rc;
1250
1251 rtSocketErrorReset();
1252#ifdef RT_OS_WINDOWS
1253 int cbNow = RT_MIN((int)cbBuffer, INT_MAX/2);
1254
1255 int cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1256
1257 if (cbWritten >= 0)
1258 {
1259 *pcbWritten = cbWritten;
1260 rc = VINF_SUCCESS;
1261 }
1262 else
1263 rc = rtSocketError();
1264
1265 if (rc == VERR_TRY_AGAIN)
1266 rc = VINF_TRY_AGAIN;
1267#else
1268 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1269 if (cbWritten >= 0)
1270 *pcbWritten = cbWritten;
1271 else if (errno == EAGAIN)
1272 {
1273 *pcbWritten = 0;
1274 rc = VINF_TRY_AGAIN;
1275 }
1276 else
1277 rc = rtSocketError();
1278#endif
1279
1280 rtSocketUnlock(pThis);
1281 return rc;
1282}
1283
1284
1285RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1286{
1287 /*
1288 * Validate input.
1289 */
1290 RTSOCKETINT *pThis = hSocket;
1291 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1292 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1293 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1294 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1295 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1296 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1297
1298 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1299 if (RT_FAILURE(rc))
1300 return rc;
1301
1302 unsigned cSegsToSend = 0;
1303 rc = VERR_NO_TMP_MEMORY;
1304#ifdef RT_OS_WINDOWS
1305 LPWSABUF paMsg = NULL;
1306
1307 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1308 if (paMsg)
1309 {
1310 DWORD dwSent = 0;
1311 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
1312 MSG_NOSIGNAL, NULL, NULL);
1313 if (!hrc)
1314 rc = VINF_SUCCESS;
1315 else
1316 rc = rtSocketError();
1317
1318 *pcbWritten = dwSent;
1319
1320 RTMemTmpFree(paMsg);
1321 }
1322
1323#else /* !RT_OS_WINDOWS */
1324 struct iovec *paMsg = NULL;
1325
1326 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1327 if (paMsg)
1328 {
1329 struct msghdr msgHdr;
1330 RT_ZERO(msgHdr);
1331 msgHdr.msg_iov = paMsg;
1332 msgHdr.msg_iovlen = cSegsToSend;
1333 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1334 if (RT_LIKELY(cbWritten >= 0))
1335 {
1336 rc = VINF_SUCCESS;
1337 *pcbWritten = cbWritten;
1338 }
1339 else
1340 rc = rtSocketError();
1341
1342 RTMemTmpFree(paMsg);
1343 }
1344#endif /* !RT_OS_WINDOWS */
1345
1346 rtSocketUnlock(pThis);
1347 return rc;
1348}
1349
1350
1351RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1352{
1353 va_list va;
1354 va_start(va, pcbWritten);
1355 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1356 va_end(va);
1357 return rc;
1358}
1359
1360
1361RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1362{
1363 /*
1364 * Set up a S/G segment array + buffer on the stack and pass it
1365 * on to RTSocketSgWrite.
1366 */
1367 Assert(cSegs <= 16);
1368 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1369 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1370 for (size_t i = 0; i < cSegs; i++)
1371 {
1372 paSegs[i].pvSeg = va_arg(va, void *);
1373 paSegs[i].cbSeg = va_arg(va, size_t);
1374 }
1375
1376 RTSGBUF SgBuf;
1377 RTSgBufInit(&SgBuf, paSegs, cSegs);
1378 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1379}
1380
1381
1382RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1383{
1384 /*
1385 * Validate input.
1386 */
1387 RTSOCKETINT *pThis = hSocket;
1388 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1389 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1390 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1391 int const fdMax = (int)pThis->hNative + 1;
1392 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1393
1394 /*
1395 * Set up the file descriptor sets and do the select.
1396 */
1397 fd_set fdsetR;
1398 FD_ZERO(&fdsetR);
1399 FD_SET(pThis->hNative, &fdsetR);
1400
1401 fd_set fdsetE = fdsetR;
1402
1403 int rc;
1404 if (cMillies == RT_INDEFINITE_WAIT)
1405 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1406 else
1407 {
1408 struct timeval timeout;
1409 timeout.tv_sec = cMillies / 1000;
1410 timeout.tv_usec = (cMillies % 1000) * 1000;
1411 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1412 }
1413 if (rc > 0)
1414 rc = VINF_SUCCESS;
1415 else if (rc == 0)
1416 rc = VERR_TIMEOUT;
1417 else
1418 rc = rtSocketError();
1419
1420 return rc;
1421}
1422
1423
1424RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents,
1425 RTMSINTERVAL cMillies)
1426{
1427 /*
1428 * Validate input.
1429 */
1430 RTSOCKETINT *pThis = hSocket;
1431 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1432 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1433 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
1434 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
1435 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1436 int const fdMax = (int)pThis->hNative + 1;
1437 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1438
1439 *pfEvents = 0;
1440
1441 /*
1442 * Set up the file descriptor sets and do the select.
1443 */
1444 fd_set fdsetR;
1445 fd_set fdsetW;
1446 fd_set fdsetE;
1447 FD_ZERO(&fdsetR);
1448 FD_ZERO(&fdsetW);
1449 FD_ZERO(&fdsetE);
1450
1451 if (fEvents & RTSOCKET_EVT_READ)
1452 FD_SET(pThis->hNative, &fdsetR);
1453 if (fEvents & RTSOCKET_EVT_WRITE)
1454 FD_SET(pThis->hNative, &fdsetW);
1455 if (fEvents & RTSOCKET_EVT_ERROR)
1456 FD_SET(pThis->hNative, &fdsetE);
1457
1458 int rc;
1459 if (cMillies == RT_INDEFINITE_WAIT)
1460 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1461 else
1462 {
1463 struct timeval timeout;
1464 timeout.tv_sec = cMillies / 1000;
1465 timeout.tv_usec = (cMillies % 1000) * 1000;
1466 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1467 }
1468 if (rc > 0)
1469 {
1470 if (FD_ISSET(pThis->hNative, &fdsetR))
1471 *pfEvents |= RTSOCKET_EVT_READ;
1472 if (FD_ISSET(pThis->hNative, &fdsetW))
1473 *pfEvents |= RTSOCKET_EVT_WRITE;
1474 if (FD_ISSET(pThis->hNative, &fdsetE))
1475 *pfEvents |= RTSOCKET_EVT_ERROR;
1476
1477 rc = VINF_SUCCESS;
1478 }
1479 else if (rc == 0)
1480 rc = VERR_TIMEOUT;
1481 else
1482 rc = rtSocketError();
1483
1484 return rc;
1485}
1486
1487
1488RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1489{
1490 /*
1491 * Validate input, don't lock it because we might want to interrupt a call
1492 * active on a different thread.
1493 */
1494 RTSOCKETINT *pThis = hSocket;
1495 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1496 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1497 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1498 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1499
1500 /*
1501 * Do the job.
1502 */
1503 int rc = VINF_SUCCESS;
1504 int fHow;
1505 if (fRead && fWrite)
1506 fHow = SHUT_RDWR;
1507 else if (fRead)
1508 fHow = SHUT_RD;
1509 else
1510 fHow = SHUT_WR;
1511 if (shutdown(pThis->hNative, fHow) == -1)
1512 rc = rtSocketError();
1513
1514 return rc;
1515}
1516
1517
1518RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1519{
1520 /*
1521 * Validate input.
1522 */
1523 RTSOCKETINT *pThis = hSocket;
1524 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1525 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1526 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1527
1528 /*
1529 * Get the address and convert it.
1530 */
1531 int rc;
1532 RTSOCKADDRUNION u;
1533#ifdef RT_OS_WINDOWS
1534 int cbAddr = sizeof(u);
1535#else
1536 socklen_t cbAddr = sizeof(u);
1537#endif
1538 RT_ZERO(u);
1539 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1540 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1541 else
1542 rc = rtSocketError();
1543
1544 return rc;
1545}
1546
1547
1548RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1549{
1550 /*
1551 * Validate input.
1552 */
1553 RTSOCKETINT *pThis = hSocket;
1554 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1555 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1556 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1557
1558 /*
1559 * Get the address and convert it.
1560 */
1561 int rc;
1562 RTSOCKADDRUNION u;
1563#ifdef RT_OS_WINDOWS
1564 int cbAddr = sizeof(u);
1565#else
1566 socklen_t cbAddr = sizeof(u);
1567#endif
1568 RT_ZERO(u);
1569 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1570 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1571 else
1572 rc = rtSocketError();
1573
1574 return rc;
1575}
1576
1577
1578
1579/**
1580 * Wrapper around bind.
1581 *
1582 * @returns IPRT status code.
1583 * @param hSocket The socket handle.
1584 * @param pAddr The address to bind to.
1585 */
1586int rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1587{
1588 /*
1589 * Validate input.
1590 */
1591 RTSOCKETINT *pThis = hSocket;
1592 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1593 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1594 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1595
1596 RTSOCKADDRUNION u;
1597 int cbAddr;
1598 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1599 if (RT_SUCCESS(rc))
1600 {
1601 if (bind(pThis->hNative, &u.Addr, cbAddr) != 0)
1602 rc = rtSocketError();
1603 }
1604
1605 rtSocketUnlock(pThis);
1606 return rc;
1607}
1608
1609
1610/**
1611 * Wrapper around listen.
1612 *
1613 * @returns IPRT status code.
1614 * @param hSocket The socket handle.
1615 * @param cMaxPending The max number of pending connections.
1616 */
1617int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1618{
1619 /*
1620 * Validate input.
1621 */
1622 RTSOCKETINT *pThis = hSocket;
1623 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1624 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1625 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1626
1627 int rc = VINF_SUCCESS;
1628 if (listen(pThis->hNative, cMaxPending) != 0)
1629 rc = rtSocketError();
1630
1631 rtSocketUnlock(pThis);
1632 return rc;
1633}
1634
1635
1636/**
1637 * Wrapper around accept.
1638 *
1639 * @returns IPRT status code.
1640 * @param hSocket The socket handle.
1641 * @param phClient Where to return the client socket handle on
1642 * success.
1643 * @param pAddr Where to return the client address.
1644 * @param pcbAddr On input this gives the size buffer size of what
1645 * @a pAddr point to. On return this contains the
1646 * size of what's stored at @a pAddr.
1647 */
1648int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1649{
1650 /*
1651 * Validate input.
1652 * Only lock the socket temporarily while we get the native handle, so that
1653 * we can safely shutdown and destroy the socket from a different thread.
1654 */
1655 RTSOCKETINT *pThis = hSocket;
1656 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1657 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1658 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1659
1660 /*
1661 * Call accept().
1662 */
1663 rtSocketErrorReset();
1664 int rc = VINF_SUCCESS;
1665#ifdef RT_OS_WINDOWS
1666 int cbAddr = (int)*pcbAddr;
1667#else
1668 socklen_t cbAddr = *pcbAddr;
1669#endif
1670 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1671 if (hNativeClient != NIL_RTSOCKETNATIVE)
1672 {
1673 *pcbAddr = cbAddr;
1674
1675 /*
1676 * Wrap the client socket.
1677 */
1678 rc = rtSocketCreateForNative(phClient, hNativeClient);
1679 if (RT_FAILURE(rc))
1680 {
1681#ifdef RT_OS_WINDOWS
1682 closesocket(hNativeClient);
1683#else
1684 close(hNativeClient);
1685#endif
1686 }
1687 }
1688 else
1689 rc = rtSocketError();
1690
1691 rtSocketUnlock(pThis);
1692 return rc;
1693}
1694
1695
1696/**
1697 * Wrapper around connect.
1698 *
1699 * @returns IPRT status code.
1700 * @param hSocket The socket handle.
1701 * @param pAddr The socket address to connect to.
1702 */
1703int rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr)
1704{
1705 /*
1706 * Validate input.
1707 */
1708 RTSOCKETINT *pThis = hSocket;
1709 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1710 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1711 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1712
1713 RTSOCKADDRUNION u;
1714 int cbAddr;
1715 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1716 if (RT_SUCCESS(rc))
1717 {
1718 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1719 rc = rtSocketError();
1720 }
1721
1722 rtSocketUnlock(pThis);
1723 return rc;
1724}
1725
1726
1727/**
1728 * Wrapper around setsockopt.
1729 *
1730 * @returns IPRT status code.
1731 * @param hSocket The socket handle.
1732 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1733 * @param iOption The option, e.g. TCP_NODELAY.
1734 * @param pvValue The value buffer.
1735 * @param cbValue The size of the value pointed to by pvValue.
1736 */
1737int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1738{
1739 /*
1740 * Validate input.
1741 */
1742 RTSOCKETINT *pThis = hSocket;
1743 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1744 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1745 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1746
1747 int rc = VINF_SUCCESS;
1748 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1749 rc = rtSocketError();
1750
1751 rtSocketUnlock(pThis);
1752 return rc;
1753}
1754
1755#ifdef RT_OS_WINDOWS
1756
1757/**
1758 * Internal RTPollSetAdd helper that returns the handle that should be added to
1759 * the pollset.
1760 *
1761 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1762 * @param hSocket The socket handle.
1763 * @param fEvents The events we're polling for.
1764 * @param ph where to put the primary handle.
1765 */
1766int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1767{
1768 RTSOCKETINT *pThis = hSocket;
1769 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1770 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1771 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1772
1773 int rc = VINF_SUCCESS;
1774 if (pThis->hEvent != WSA_INVALID_EVENT)
1775 *ph = pThis->hEvent;
1776 else
1777 {
1778 *ph = pThis->hEvent = WSACreateEvent();
1779 if (pThis->hEvent == WSA_INVALID_EVENT)
1780 rc = rtSocketError();
1781 }
1782
1783 rtSocketUnlock(pThis);
1784 return rc;
1785}
1786
1787
1788/**
1789 * Undos the harm done by WSAEventSelect.
1790 *
1791 * @returns IPRT status code.
1792 * @param pThis The socket handle.
1793 */
1794static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1795{
1796 int rc = VINF_SUCCESS;
1797 if (pThis->fSubscribedEvts)
1798 {
1799 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1800 {
1801 pThis->fSubscribedEvts = 0;
1802
1803 /*
1804 * Switch back to blocking mode if that was the state before the
1805 * operation.
1806 */
1807 if (pThis->fBlocking)
1808 {
1809 u_long fNonBlocking = 0;
1810 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1811 if (rc2 != 0)
1812 {
1813 rc = rtSocketError();
1814 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1815 }
1816 }
1817 }
1818 else
1819 {
1820 rc = rtSocketError();
1821 AssertMsgFailed(("%Rrc\n", rc));
1822 }
1823 }
1824 return rc;
1825}
1826
1827
1828/**
1829 * Updates the mask of events we're subscribing to.
1830 *
1831 * @returns IPRT status code.
1832 * @param pThis The socket handle.
1833 * @param fEvents The events we want to subscribe to.
1834 */
1835static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1836{
1837 LONG fNetworkEvents = 0;
1838 if (fEvents & RTPOLL_EVT_READ)
1839 fNetworkEvents |= FD_READ;
1840 if (fEvents & RTPOLL_EVT_WRITE)
1841 fNetworkEvents |= FD_WRITE;
1842 if (fEvents & RTPOLL_EVT_ERROR)
1843 fNetworkEvents |= FD_CLOSE;
1844 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
1845 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1846 {
1847 pThis->fSubscribedEvts = fEvents;
1848 return VINF_SUCCESS;
1849 }
1850
1851 int rc = rtSocketError();
1852 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1853 return rc;
1854}
1855
1856
1857/**
1858 * Checks for pending events.
1859 *
1860 * @returns Event mask or 0.
1861 * @param pThis The socket handle.
1862 * @param fEvents The desired events.
1863 */
1864static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1865{
1866 int rc = VINF_SUCCESS;
1867 uint32_t fRetEvents = 0;
1868
1869 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
1870
1871 /* Make sure WSAEnumNetworkEvents returns what we want. */
1872 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1873 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1874
1875 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1876 WSANETWORKEVENTS NetEvts;
1877 RT_ZERO(NetEvts);
1878 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1879 {
1880 if ( (NetEvts.lNetworkEvents & FD_READ)
1881 && (fEvents & RTPOLL_EVT_READ)
1882 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1883 fRetEvents |= RTPOLL_EVT_READ;
1884
1885 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1886 && (fEvents & RTPOLL_EVT_WRITE)
1887 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1888 fRetEvents |= RTPOLL_EVT_WRITE;
1889
1890 if (fEvents & RTPOLL_EVT_ERROR)
1891 {
1892 if (NetEvts.lNetworkEvents & FD_CLOSE)
1893 fRetEvents |= RTPOLL_EVT_ERROR;
1894 else
1895 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1896 if ( (NetEvts.lNetworkEvents & (1L << i))
1897 && NetEvts.iErrorCode[i] != 0)
1898 fRetEvents |= RTPOLL_EVT_ERROR;
1899 }
1900 }
1901 else
1902 rc = rtSocketError();
1903
1904 /* Fall back on select if we hit an error above. */
1905 if (RT_FAILURE(rc))
1906 {
1907 /** @todo */
1908 }
1909
1910 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
1911 return fRetEvents;
1912}
1913
1914
1915/**
1916 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1917 * clear, starts whatever actions we've got running during the poll call.
1918 *
1919 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1920 * Event mask (in @a fEvents) and no actions if the handle is ready
1921 * already.
1922 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1923 * different poll set.
1924 *
1925 * @param hSocket The socket handle.
1926 * @param hPollSet The poll set handle (for access checks).
1927 * @param fEvents The events we're polling for.
1928 * @param fFinalEntry Set if this is the final entry for this handle
1929 * in this poll set. This can be used for dealing
1930 * with duplicate entries.
1931 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1932 * we'll wait for an event to occur.
1933 *
1934 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1935 * @c true, we don't currently care about that oddity...
1936 */
1937uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1938{
1939 RTSOCKETINT *pThis = hSocket;
1940 AssertPtrReturn(pThis, UINT32_MAX);
1941 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1942 if (rtSocketTryLock(pThis))
1943 pThis->hPollSet = hPollSet;
1944 else
1945 {
1946 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1947 ASMAtomicIncU32(&pThis->cUsers);
1948 }
1949
1950 /* (rtSocketPollCheck will reset the event object). */
1951 uint32_t fRetEvents = pThis->fEventsSaved;
1952 pThis->fEventsSaved = 0; /* Reset */
1953 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
1954
1955 if ( !fRetEvents
1956 && !fNoWait)
1957 {
1958 pThis->fPollEvts |= fEvents;
1959 if ( fFinalEntry
1960 && pThis->fSubscribedEvts != pThis->fPollEvts)
1961 {
1962 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1963 if (RT_FAILURE(rc))
1964 {
1965 pThis->fPollEvts = 0;
1966 fRetEvents = UINT32_MAX;
1967 }
1968 }
1969 }
1970
1971 if (fRetEvents || fNoWait)
1972 {
1973 if (pThis->cUsers == 1)
1974 {
1975 rtSocketPollClearEventAndRestoreBlocking(pThis);
1976 pThis->hPollSet = NIL_RTPOLLSET;
1977 }
1978 ASMAtomicDecU32(&pThis->cUsers);
1979 }
1980
1981 return fRetEvents;
1982}
1983
1984
1985/**
1986 * Called after a WaitForMultipleObjects returned in order to check for pending
1987 * events and stop whatever actions that rtSocketPollStart() initiated.
1988 *
1989 * @returns Event mask or 0.
1990 *
1991 * @param hSocket The socket handle.
1992 * @param fEvents The events we're polling for.
1993 * @param fFinalEntry Set if this is the final entry for this handle
1994 * in this poll set. This can be used for dealing
1995 * with duplicate entries. Only keep in mind that
1996 * this method is called in reverse order, so the
1997 * first call will have this set (when the entire
1998 * set was processed).
1999 * @param fHarvestEvents Set if we should check for pending events.
2000 */
2001uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2002{
2003 RTSOCKETINT *pThis = hSocket;
2004 AssertPtrReturn(pThis, 0);
2005 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2006 Assert(pThis->cUsers > 0);
2007 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2008
2009 /* Harvest events and clear the event mask for the next round of polling. */
2010 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2011 pThis->fPollEvts = 0;
2012
2013 /*
2014 * Save the write event if required.
2015 * It is only posted once and might get lost if the another source in the
2016 * pollset with a higher priority has pending events.
2017 */
2018 if ( !fHarvestEvents
2019 && fRetEvents)
2020 {
2021 pThis->fEventsSaved = fRetEvents;
2022 fRetEvents = 0;
2023 }
2024
2025 /* Make the socket blocking again and unlock the handle. */
2026 if (pThis->cUsers == 1)
2027 {
2028 rtSocketPollClearEventAndRestoreBlocking(pThis);
2029 pThis->hPollSet = NIL_RTPOLLSET;
2030 }
2031 ASMAtomicDecU32(&pThis->cUsers);
2032 return fRetEvents;
2033}
2034
2035#endif /* RT_OS_WINDOWS */
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